<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="ansible入门, 博客，个人经验分离，kubernetes,k8s,Linux运维，Python">
    <meta name="description" content="
万字干货 - 提升十倍运维效率 - Ansible 入门到精通


Ansible 命令使用
Ansible 常用模块详解
YAML 语法简介
Ansible playbook 基础
Playbook 变量、tags、handlers 使">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="referrer" content="no-referrer-when-downgrade">
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>ansible入门 | 躺平的人生</title>
    <link rel="icon" type="image/png" href="/favicon.png">
    


    <!-- bg-cover style     -->



<link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.min.css">
<link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
<link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
<link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
<link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
<link rel="stylesheet" type="text/css" href="/css/matery.css">
<link rel="stylesheet" type="text/css" href="/css/my.css">
<link rel="stylesheet" type="text/css" href="/css/dark.css" media="none" onload="if(media!='all')media='all'">




    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
    <link rel="stylesheet" href="/css/post.css">




    
        <link rel="stylesheet" type="text/css" href="/css/reward.css">
    



    <script src="/libs/jquery/jquery-3.6.0.min.js"></script>

<meta name="generator" content="Hexo 6.3.0"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">躺平的人生</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
  <li>
    <a href="javascript:;" class="waves-effect waves-light" onclick="switchNightMode()" title="深色/浅色模式" >
      <i id="sum-moon-icon" class="fas fa-sun" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">躺平的人生</div>
        <div class="logo-desc">
            
            本站记录本人各种学习的旅途，笔记，用于巩固自我并启发后来人
            
        </div>
    </div>

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
        <li><div class="divider"></div></li>
        <li>
            <a href="https://miaohsukang.gitee.io" class="waves-effect waves-light" target="_blank">
                <i class="fab fa-github-square fa-fw"></i>Fork Me
            </a>
        </li>
        
    </ul>
</div>


        </div>

        
            <style>
    .nav-transparent .github-corner {
        display: none !important;
    }

    .github-corner {
        position: absolute;
        z-index: 10;
        top: 0;
        right: 0;
        border: 0;
        transform: scale(1.1);
    }

    .github-corner svg {
        color: #F062A7;
        fill: #fff;
        height: 64px;
        width: 64px;
    }

    .github-corner:hover .octo-arm {
        animation: a 0.56s ease-in-out;
    }

    .github-corner .octo-arm {
        animation: none;
    }

    @keyframes a {
        0%,
        to {
            transform: rotate(0);
        }
        20%,
        60% {
            transform: rotate(-25deg);
        }
        40%,
        80% {
            transform: rotate(10deg);
        }
    }
</style>

<a href="https://miaohsukang.gitee.io" class="github-corner tooltipped hide-on-med-and-down" target="_blank"
   data-tooltip="Fork Me" data-position="left" data-delay="50">
    <svg viewBox="0 0 250 250" aria-hidden="true">
        <path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
        <path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2"
              fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
        <path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z"
              fill="currentColor" class="octo-body"></path>
    </svg>
</a>
        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('请输入访问本文章的密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误，将返回主页！');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('https://ts1.cn.mm.bing.net/th/id/R-C.20481cfcdffccefff9e7bd7bb322a0dd?rik=8xIugUv4zxwdGQ&riu=http%3a%2f%2fjust4coding.com%2fimages%2f2017-09-14%2f1.png&ehk=68x7iYnQrijvElEedtUB27olRYyMZCR8v%2feKXk9XtO0%3d&risl=&pid=ImgRaw&r=0')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">ansible入门</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/ansible/">
                                <span class="chip bg-color">ansible</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Ansible/" class="post-category">
                                Ansible
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2023-02-12
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2023-02-12
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    13.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    67 分
                </div>
                

                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
        </div>
        <hr class="clearfix">

        
        <!-- 是否加载使用自带的 prismjs. -->
        <link rel="stylesheet" href="/libs/prism/prism.min.css">
        

        

        <div class="card-content article-card-content">
            <div id="articleContent">
                <blockquote>
<p><strong>万字干货 - 提升十倍运维效率 - Ansible 入门到精通</strong></p>
</blockquote>
<ul>
<li><h4 id="Ansible-命令使用"><a href="#Ansible-命令使用" class="headerlink" title="Ansible 命令使用"></a>Ansible 命令使用</h4></li>
<li><h4 id="Ansible-常用模块详解"><a href="#Ansible-常用模块详解" class="headerlink" title="Ansible 常用模块详解"></a>Ansible 常用模块详解</h4></li>
<li><h4 id="YAML-语法简介"><a href="#YAML-语法简介" class="headerlink" title="YAML 语法简介"></a>YAML 语法简介</h4></li>
<li><h4 id="Ansible-playbook-基础"><a href="#Ansible-playbook-基础" class="headerlink" title="Ansible playbook 基础"></a>Ansible playbook 基础</h4></li>
<li><h4 id="Playbook-变量、tags、handlers-使用"><a href="#Playbook-变量、tags、handlers-使用" class="headerlink" title="Playbook 变量、tags、handlers 使用"></a>Playbook 变量、tags、handlers 使用</h4></li>
<li><h4 id="Playbook-模板-templates"><a href="#Playbook-模板-templates" class="headerlink" title="Playbook 模板 templates"></a>Playbook 模板 templates</h4></li>
<li><h4 id="Playbook-条件判断-when"><a href="#Playbook-条件判断-when" class="headerlink" title="Playbook 条件判断 when"></a>Playbook 条件判断 when</h4></li>
<li><h4 id="Playbook-字典-with-items"><a href="#Playbook-字典-with-items" class="headerlink" title="Playbook 字典 with_items"></a>Playbook 字典 with_items</h4></li>
<li><h4 id="Ansible-Roles"><a href="#Ansible-Roles" class="headerlink" title="Ansible Roles"></a>Ansible Roles</h4></li>
</ul>
<p><strong>相关工具</strong></p>
<ul>
<li>代码管理（SCM）：GitHub、GitLab、BitBucket、SubVersion</li>
<li>构建工具：maven、Ant、Gradle</li>
<li>自动部署：Capistrano、CodeDeploy</li>
<li>持续集成（CI）：Jenkins、Travis</li>
<li>配置管理：Ansible、SaltStack、Chef、Puppet</li>
<li>容器：Docker、Podman、LXC、第三方厂商如 AWS</li>
<li>编排：Kubernetes、Core、Apache Mesos</li>
<li>服务注册与发现：Zookeeper、etcd、Consul</li>
<li>脚本语言：python、ruby、shell</li>
<li>日志管理：ELK、Logentries</li>
<li>系统监控：Prometheus、Zabbix、Datadog、Graphite、Ganglia、Nagios</li>
<li>性能监控：AppDynamics、New Relic、Splunk</li>
<li>压力测试：JMeter、Blaze Meter、loader.io</li>
<li>应用服务器：Tomcat、JBoss、IIS</li>
<li>Web 服务器：Apache、Nginx</li>
<li>数据库：MySQL、Oracle、PostgreSQL 等关系型数据库；mongoDB、redis 等 NoSQL 数据库</li>
<li>项目管理（PM）：Jira、Asana、Taiga、Trello、Basecamp、Pivotal Tracker</li>
</ul>
<hr>
<h3 id="一、Ansible-介绍和架构"><a href="#一、Ansible-介绍和架构" class="headerlink" title="一、Ansible 介绍和架构"></a>一、Ansible 介绍和架构</h3><p>公司计划在年底做一次大型市场促销活动，全面冲刺下交易额，为明年的上市做准备。公司要求各业务组对年底大促做准备，运维部要求所有业务容量进行三倍的扩容，并搭建出多套环境可以共开发和测试人员做测试，运维老大为了在年底有所表现，要求运维部门同学尽快实现，当你接到这个任务时，有没有更快的解决方案？</p>
<h4 id="1-1-Ansible-发展史"><a href="#1-1-Ansible-发展史" class="headerlink" title="1.1 Ansible 发展史"></a>1.1 Ansible 发展史</h4><p>作者：Michael DeHaan（ Cobbler 与 Func 作者）</p>
<p>ansible 的名称来自科幻小说《安德的游戏》中跨越时空的即时通信工具，使用它可以在相距数光年的距离，远程实时控制前线的舰队战斗。</p>
<p>2012-03-09，发布 0.0.1 版，2015-10-17，Red Hat 宣布 1.5 亿美元收购</p>
<p>官网：<a target="_blank" rel="noopener" href="https://www.ansible.com/">https://www.ansible.com/</a> 官方文档：<a target="_blank" rel="noopener" href="https://docs.ansible.com/">https://docs.ansible.com/</a></p>
<h4 id="1-2-Ansible-特性"><a href="#1-2-Ansible-特性" class="headerlink" title="1.2 Ansible 特性"></a>1.2 Ansible 特性</h4><ul>
<li>模块化：调用特定的模块完成特定任务，支持自定义模块，可使用任何编程语言写模块</li>
<li>Paramiko（python 对 ssh 的实现），PyYAML，Jinja2（模板语言）三个关键模块</li>
<li>基于 Python 语言实现</li>
<li>部署简单，基于 python 和 SSH(默认已安装)，agentless，无需代理不依赖 PKI（无需 ssl）</li>
<li>安全，基于 OpenSSH</li>
<li>幂等性：一个任务执行 1 遍和执行 n 遍效果一样，不因重复执行带来意外情况</li>
<li>支持 playbook 编排任务，YAML 格式，编排任务，支持丰富的数据结构</li>
<li>较强大的多层解决方案 role</li>
</ul>
<h4 id="1-3-Ansible-架构"><a href="#1-3-Ansible-架构" class="headerlink" title="1.3 Ansible 架构"></a>1.3 Ansible 架构</h4><h5 id="1-3-1-Ansible-组成"><a href="#1-3-1-Ansible-组成" class="headerlink" title="1.3.1 Ansible 组成"></a>1.3.1 Ansible 组成</h5><p><img src="https://gitee.com/miaohsukang/myblog/raw/master/img/20200609220050772.png"></p>
<p>组合 INVENTORY、API、MODULES、PLUGINS 的绿框，可以理解为是 ansible 命令工具，其为核心执行工具</p>
<ul>
<li>INVENTORY：Ansible 管理主机的清单 &#x2F; etc&#x2F;anaible&#x2F;hosts</li>
<li>MODULES：Ansible 执行命令的功能模块，多数为内置核心模块，也可自定义</li>
<li>PLUGINS：模块功能的补充，如连接类型插件、循环插件、变量插件、过滤插件等，该功能不常用</li>
<li>API：供第三方程序调用的应用程序编程接口</li>
</ul>
<h5 id="1-3-2-Ansible-命令执行来源"><a href="#1-3-2-Ansible-命令执行来源" class="headerlink" title="1.3.2 Ansible 命令执行来源"></a>1.3.2 Ansible 命令执行来源</h5><ul>
<li>USER 普通用户，即 SYSTEM ADMINISTRATOR</li>
<li>PLAYBOOKS：任务剧本（任务集），编排定义 Ansible 任务集的配置文件，由 Ansible 顺序依次执行，通常是 JSON 格式的 YML 文件</li>
<li>CMDB（配置管理数据库） API 调用</li>
<li>PUBLIC&#x2F;PRIVATE CLOUD API 调用</li>
<li>USER-&gt; Ansible Playbook -&gt; Ansibile</li>
</ul>
<h5 id="1-3-3-注意事项"><a href="#1-3-3-注意事项" class="headerlink" title="1.3.3 注意事项"></a>1.3.3 注意事项</h5><ul>
<li>执行 ansible 的主机一般称为主控端，中控，master 或堡垒机</li>
<li>主控端 Python 版本需要 2.6 或以上</li>
<li>被控端 Python 版本小于 2.4，需要安装 python-simplejson</li>
<li>被控端如开启 SELinux 需要安装 libselinux-python</li>
<li>windows 不能做为主控端</li>
</ul>
<h3 id="二、Ansible-安装和入门"><a href="#二、Ansible-安装和入门" class="headerlink" title="二、Ansible 安装和入门"></a>二、Ansible 安装和入门</h3><h4 id="2-1-Ansible-安装"><a href="#2-1-Ansible-安装" class="headerlink" title="2.1 Ansible 安装"></a>2.1 Ansible 安装</h4><p>ansible 的安装方法有多种</p>
<h5 id="2-1-1-EPEL-源的-rpm-包安装"><a href="#2-1-1-EPEL-源的-rpm-包安装" class="headerlink" title="2.1.1 EPEL 源的 rpm 包安装"></a>2.1.1 EPEL 源的 rpm 包安装</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment"># yum install ansible</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="2-1-2-编译安装"><a href="#2-1-2-编译安装" class="headerlink" title="2.1.2 编译安装"></a>2.1.2 编译安装</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">yum <span class="token parameter variable">-y</span> <span class="token function">install</span> python-jinja2 PyYAML python-paramiko python-babel python-crypto
<span class="token function">tar</span> xf ansible-1.5.4.tar.gz
<span class="token builtin class-name">cd</span> ansible-1.5.4
python setup.py build
python setup.py <span class="token function">install</span>
<span class="token function">mkdir</span> /etc/ansible
<span class="token function">cp</span> <span class="token parameter variable">-r</span> examples/* /etc/ansible<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-1-3-Git-方式"><a href="#2-1-3-Git-方式" class="headerlink" title="2.1.3 Git 方式"></a>2.1.3 Git 方式</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">git</span> clone git://github.com/ansible/ansible.git <span class="token parameter variable">--recursive</span>
<span class="token builtin class-name">cd</span> ./ansible
<span class="token builtin class-name">source</span> ./hacking/env-setup<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h5 id="2-1-4-pip-安装"><a href="#2-1-4-pip-安装" class="headerlink" title="2.1.4 pip 安装"></a>2.1.4 pip 安装</h5><p>pip 是安装 Python 包的管理器，类似 yum</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">yum <span class="token function">install</span> python-pip python-devel
yum <span class="token function">install</span> gcc glibc-devel zibl-devel  rpm-bulid openssl-devel
pip <span class="token function">install</span>  <span class="token parameter variable">--upgrade</span> pip
pip <span class="token function">install</span> ansible <span class="token parameter variable">--upgrade</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-1-5-确认安装"><a href="#2-1-5-确认安装" class="headerlink" title="2.1.5 确认安装"></a>2.1.5 确认安装</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible --version</span>
ansible <span class="token number">2.9</span>.7
  config <span class="token function">file</span> <span class="token operator">=</span> /etc/ansible/ansible.cfg
  configured module search path <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">'/root/.ansible/plugins/modules'</span>, <span class="token string">'/usr/share/ansible/plugins/modules'</span><span class="token punctuation">]</span>
  ansible python module location <span class="token operator">=</span> /usr/lib/python3.6/site-packages/ansible
  executable location <span class="token operator">=</span> /usr/bin/ansible
  python version <span class="token operator">=</span> <span class="token number">3.6</span>.8 <span class="token punctuation">(</span>default, Oct <span class="token number">11</span> <span class="token number">2019</span>, <span class="token number">15</span>:04:54<span class="token punctuation">)</span> <span class="token punctuation">[</span>GCC <span class="token number">8.3</span>.1 <span class="token number">20190507</span> <span class="token punctuation">(</span>Red Hat <span class="token number">8.3</span>.1-4<span class="token punctuation">)</span><span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-2-Ansible-相关文件"><a href="#2-2-Ansible-相关文件" class="headerlink" title="2.2 Ansible 相关文件"></a>2.2 Ansible 相关文件</h4><h5 id="2-2-1-配置文件"><a href="#2-2-1-配置文件" class="headerlink" title="2.2.1 配置文件"></a>2.2.1 配置文件</h5><ul>
<li>&#x2F;etc&#x2F;ansible&#x2F;ansible.cfg 主配置文件，配置 ansible 工作特性</li>
<li>&#x2F;etc&#x2F;ansible&#x2F;hosts 主机清单</li>
<li>&#x2F;etc&#x2F;ansible&#x2F;roles&#x2F; 存放角色的目录(建议)</li>
</ul>
<h5 id="2-2-2-ansible-主配置文件"><a href="#2-2-2-ansible-主配置文件" class="headerlink" title="2.2.2 ansible 主配置文件"></a>2.2.2 ansible 主配置文件</h5><p>Ansible 的配置文件<code>/etc/ansible/ansible.cfg</code>, 其中大部分的配置内容无需进行修改</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>defaults<span class="token punctuation">]</span>
<span class="token comment">#inventory      = /etc/ansible/hosts  # 主机列表配置文件</span>
<span class="token comment">#library  = /usr/share/my_modules/ # 库文件存放目录</span>
<span class="token comment">#remote_tmp  = $HOME/.ansible/tmp  #临时py命令文件存放在远程主机目录</span>
<span class="token comment">#local_tmp      = $HOME/.ansible/tmp # 本机的临时命令执行目录</span>
<span class="token comment">#forks          = 5       # 默认并发数</span>
<span class="token comment">#sudo_user      = root      # 默认sudo 用户</span>
<span class="token comment">#ask_sudo_pass = True  #每次执行ansible命令是否询问ssh密码</span>
<span class="token comment">#ask_pass      = True</span>
<span class="token comment">#remote_port    = 22</span>
<span class="token comment">#host_key_checking = False  # 检查对应服务器的host_key，建议取消注释</span>
<span class="token comment">#log_path=/var/log/ansible.log  #日志文件，建议启用</span>
<span class="token comment">#module_name = command   #默认模块，可以修改为shell模块</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-2-3-inventory-主机清单"><a href="#2-2-3-inventory-主机清单" class="headerlink" title="2.2.3 inventory 主机清单"></a>2.2.3 inventory 主机清单</h5><p>ansible 的主要功用在于批量主机操作，为了便捷地使用其中的部分主机，可以在 inventory file 中将其分组命名 默认的 inventory file 为<code>/etc/ansible/hosts</code> inventory file 可以有多个，且也可以通过 Dynamic Inventory 来动态生成</p>
<p><strong>主机清单文件格式</strong></p>
<p>inventory 文件遵循 INI 文件风格，中括号中的字符为组名。可以将同一个主机同时归并到多个不同的组中</p>
<p>此外，当如若目标主机使用了非默认的 SSH 端口，还可以在主机名称之后使用冒号加端口号来标明</p>
<p>如果主机名称遵循相似的命名模式，还可以使用列表的方式标识各主机</p>
<p>范例：</p>
<pre class="line-numbers language-none"><code class="language-none">ntp.magedu.com
[webservers]
www1.magedu.com:2222
www2.magedu.com

[dbservers]
db1.magedu.com
db2.magedu.com
db3.magedu.com

[websrvs]
www[1:100].example.com

[dbsrvs]
db-[a:f].example.com

[appsrvs]
10.0.0.[1:100]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-3-Ansible-相关工具"><a href="#2-3-Ansible-相关工具" class="headerlink" title="2.3 Ansible 相关工具"></a>2.3 Ansible 相关工具</h4><ul>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible 主程序，临时命令执行工具</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-doc 查看配置文档，模块功能查看工具</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-galaxy 下载 &#x2F; 上传优秀代码或 Roles 模块的官网平台</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-playbook 定制自动化任务，编排剧本工具</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-pull 远程执行命令的工具</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-vault 文件加密工具</li>
<li>&#x2F;usr&#x2F;bin&#x2F;ansible-console 基于 Console 界面与用户交互的执行工具</li>
</ul>
<p><strong>利用 ansible 实现管理的主要方式：</strong></p>
<ul>
<li>Ad-Hoc 即利用 ansible 命令，主要用于临时命令使用场景</li>
<li>Ansible-playbook 主要用于长期规划好的，大型项目的场景，需要有前期的规划过程</li>
</ul>
<h5 id="2-3-1-ansible-doc"><a href="#2-3-1-ansible-doc" class="headerlink" title="2.3.1 ansible-doc"></a>2.3.1 ansible-doc</h5><p>此工具用来显示模块帮助</p>
<p>格式</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible-doc <span class="token punctuation">[</span>options<span class="token punctuation">]</span> <span class="token punctuation">[</span>module<span class="token punctuation">..</span>.<span class="token punctuation">]</span>
-l, <span class="token parameter variable">--list</span>           <span class="token comment"># 列出可用模块</span>
-s, <span class="token parameter variable">--snippet</span>        <span class="token comment"># 显示指定模块的playbook片段</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 列出所有模块</span>
ansible-doc <span class="token parameter variable">-l</span>
<span class="token comment"># 查看指定模块帮助用法</span>
ansible-doc <span class="token function">ping</span>  
<span class="token comment"># 查看指定模块简单帮助用法</span>
ansible-doc <span class="token parameter variable">-s</span>  <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-3-2-ansible"><a href="#2-3-2-ansible" class="headerlink" title="2.3.2 ansible"></a>2.3.2 ansible</h5><p>此工具通过 ssh 协议，实现对远程主机的配置管理、应用部署、任务执行等功能</p>
<p>建议：使用此工具前，先配置 ansible 主控端能基于密钥认证的方式联系各个被管理节点</p>
<p>范例：利用 sshpass 批量实现基于 key 验证</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token shebang important">#!/bin/bash</span>
ssh-keygen <span class="token parameter variable">-f</span> /root/.ssh/id_rsa  <span class="token parameter variable">-P</span> <span class="token string">''</span>
<span class="token assign-left variable">NET</span><span class="token operator">=</span><span class="token number">192.168</span>.100
<span class="token builtin class-name">export</span> <span class="token assign-left variable">SSHPASS</span><span class="token operator">=</span>magedu
<span class="token keyword">for</span> <span class="token for-or-select variable">IP</span> <span class="token keyword">in</span> <span class="token punctuation">&#123;</span><span class="token number">1</span><span class="token punctuation">..</span><span class="token number">200</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span class="token keyword">do</span> 
    sshpass <span class="token parameter variable">-e</span> ssh-copy-id  <span class="token variable">$NET</span><span class="token builtin class-name">.</span><span class="token variable">$IP</span> 
<span class="token keyword">done</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>格式：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible <span class="token operator">&lt;</span>host-pattern<span class="token operator">></span> <span class="token punctuation">[</span>-m module_name<span class="token punctuation">]</span> <span class="token punctuation">[</span>-a args<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>选项说明：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token parameter variable">--version</span>           <span class="token comment"># 显示版本</span>
<span class="token parameter variable">-m</span> module           <span class="token comment"># 指定模块，默认为command</span>
<span class="token parameter variable">-v</span>                  <span class="token comment"># 详细过程 –vv  -vvv更详细</span>
--list-hosts        <span class="token comment"># 显示主机列表，可简写 --list</span>
-k, --ask-pass      <span class="token comment"># 提示输入ssh连接密码，默认Key验证</span>
-C, <span class="token parameter variable">--check</span>         <span class="token comment"># 检查，并不执行</span>
-T, <span class="token parameter variable">--timeout</span><span class="token operator">=</span>TIMEOUT   <span class="token comment"># 执行命令的超时时间，默认10s</span>
-u, <span class="token parameter variable">--user</span><span class="token operator">=</span>REMOTE_USER  <span class="token comment"># 执行远程执行的用户</span>
-b, <span class="token parameter variable">--become</span>            <span class="token comment"># 代替旧版的sudo 切换</span>
--become-user<span class="token operator">=</span>USERNAME  <span class="token comment"># 指定sudo的runas用户，默认为root</span>
-K, --ask-become-pass   <span class="token comment"># 提示输入sudo时的口令</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>ansible 的 Host-pattern 用于匹配被控制的主机的列表 All ：表示所有 Inventory 中的所有主机</p>
<p>范例</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all –m <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>输出问题</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@xuegod ~<span class="token punctuation">]</span><span class="token comment"># ansible all -m ping</span>
<span class="token punctuation">[</span>WARNING<span class="token punctuation">]</span>: Platform linux on <span class="token function">host</span> <span class="token number">10.10</span>.30.7 is using the discovered Python interpreter at /usr/bin/python, but future installation of
another Python interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html <span class="token keyword">for</span>
<span class="token function">more</span> information.
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"ansible_facts"</span><span class="token builtin class-name">:</span> <span class="token punctuation">&#123;</span>
        <span class="token string">"discovered_interpreter_python"</span><span class="token builtin class-name">:</span> <span class="token string">"/usr/bin/python"</span>
    <span class="token punctuation">&#125;</span>,
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> false,
    <span class="token string">"ping"</span><span class="token builtin class-name">:</span> <span class="token string">"pong"</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">[</span>WARNING<span class="token punctuation">]</span>: Platform linux on <span class="token function">host</span> <span class="token number">10.10</span>.30.8 is using the discovered Python interpreter at /usr/bin/python, but future installation of
another Python interpreter could change this. See https://docs.ansible.com/ansible/2.9/reference_appendices/interpreter_discovery.html <span class="token keyword">for</span>
<span class="token function">more</span> information.
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"ansible_facts"</span><span class="token builtin class-name">:</span> <span class="token punctuation">&#123;</span>
        <span class="token string">"discovered_interpreter_python"</span><span class="token builtin class-name">:</span> <span class="token string">"/usr/bin/python"</span>
    <span class="token punctuation">&#125;</span>,
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> false,
    <span class="token string">"ping"</span><span class="token builtin class-name">:</span> <span class="token string">"pong"</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>上面的warning是python版本依赖，我们可以通过python的一个模块配置<code>ansible_python_interpreter</code>来指向python位置，就是你受管主机的python位置，如下所示</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>dbsrvs<span class="token punctuation">]</span>
<span class="token number">10.10</span>.30.8 <span class="token assign-left variable">ansible_python_interpreter</span><span class="token operator">=</span>/usr/bin/python2.7

<span class="token punctuation">[</span>websrvs<span class="token punctuation">]</span>
<span class="token number">10.10</span>.30.<span class="token punctuation">[</span><span class="token number">7</span>:8<span class="token punctuation">]</span> <span class="token assign-left variable">ansible_python_interpreter</span><span class="token operator">=</span>/usr/bin/python2.7

<span class="token punctuation">[</span>appsrvs<span class="token punctuation">]</span>
<span class="token number">10.10</span>.30.<span class="token punctuation">[</span><span class="token number">6</span>:8<span class="token punctuation">]</span> <span class="token assign-left variable">ansible_python_interpreter</span><span class="token operator">=</span>/usr/bin/python2.7<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p> 这时我们再去执行命令输出就不会有刚才那个警告出现了</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible all -m ping</span>
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> false,
    <span class="token string">"ping"</span><span class="token builtin class-name">:</span> <span class="token string">"pong"</span>
<span class="token punctuation">&#125;</span>
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> false,
    <span class="token string">"ping"</span><span class="token builtin class-name">:</span> <span class="token string">"pong"</span>
<span class="token punctuation">&#125;</span>
<span class="token number">10.10</span>.30.6 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> false,
    <span class="token string">"ping"</span><span class="token builtin class-name">:</span> <span class="token string">"pong"</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>*: 通配符</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible  “*”  <span class="token parameter variable">-m</span> <span class="token function">ping</span>
ansible  <span class="token number">192.168</span>.1.* <span class="token parameter variable">-m</span> <span class="token function">ping</span>
ansible  “srvs”  <span class="token parameter variable">-m</span> <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>或关系</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible “websrvs:appsrvs”  <span class="token parameter variable">-m</span> <span class="token function">ping</span>
ansible “192.168.1.10:192.168.1.20”  <span class="token parameter variable">-m</span> <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>逻辑与</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#在websrvs组并且在dbsrvs组中的主机</span>
ansible “websrvs:<span class="token operator">&amp;</span>dbsrvs” –m <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>逻辑非</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#在websrvs组，但不在dbsrvs组中的主机</span>
<span class="token comment">#注意：此处为单引号</span>
ansible ‘websrvs:<span class="token operator">!</span>dbsrvs’ –m <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>综合逻辑</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible ‘websrvs:dbsrvs:<span class="token operator">&amp;</span>appsrvs:<span class="token operator">!</span>ftpsrvs’ –m <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>正则表达式</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible “websrvs:dbsrvs” –m <span class="token function">ping</span> 
ansible “~<span class="token punctuation">(</span>web<span class="token operator">|</span>db<span class="token punctuation">)</span>.*<span class="token punctuation">\</span>.magedu<span class="token punctuation">\</span>.com” –m <span class="token function">ping</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><strong>ansible 命令执行过程</strong></p>
<ol>
<li>加载自己的配置文件 默认 &#x2F; etc&#x2F;ansible&#x2F;ansible.cfg</li>
<li>加载自己对应的模块文件，如：command</li>
<li>通过 ansible 将模块或命令生成对应的临时 py 文件，并将该文件传输至远程服务器的对应执行用户 $HOME&#x2F;.ansible&#x2F;tmp&#x2F;ansible-tmp - 数字 &#x2F; XXX.PY 文件</li>
<li>给文件 + x 执行</li>
<li>执行并返回结果</li>
<li>删除临时 py 文件，退出</li>
</ol>
<p>ansible 的执行状态：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@centos8 ~<span class="token punctuation">]</span><span class="token comment">#grep -A 14 '\[colors\]' /etc/ansible/ansible.cfg</span>
<span class="token punctuation">[</span>colors<span class="token punctuation">]</span>
<span class="token comment">#highlight = white</span>
<span class="token comment">#verbose = blue</span>
<span class="token comment">#warn = bright purple</span>
<span class="token comment">#error = red</span>
<span class="token comment">#debug = dark gray</span>
<span class="token comment">#deprecate = purple</span>
<span class="token comment">#skip = cyan</span>
<span class="token comment">#unreachable = red</span>
<span class="token comment">#ok = green</span>
<span class="token comment">#changed = yellow</span>
<span class="token comment">#diff_add = green</span>
<span class="token comment">#diff_remove = red</span>
<span class="token comment">#diff_lines = cyan</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<ul>
<li>绿色：执行成功并且不需要做改变的操作</li>
<li>黄色：执行成功并且对目标主机做变更</li>
<li>红色：执行失败</li>
</ul>
<p><strong>ansible 使用范例</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#以wang用户执行ping存活检测</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">ping</span> <span class="token parameter variable">-u</span> wang  <span class="token parameter variable">-k</span>
<span class="token comment">#以wang sudo至root执行ping存活检测</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">ping</span> <span class="token parameter variable">-u</span> wang <span class="token parameter variable">-k</span> <span class="token parameter variable">-b</span>
<span class="token comment">#以wang sudo至mage用户执行ping存活检测</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">ping</span> <span class="token parameter variable">-u</span> wang <span class="token parameter variable">-k</span> <span class="token parameter variable">-b</span> --become-user<span class="token operator">=</span>mage
<span class="token comment">#以wang sudo至root用户执行ls</span>
ansible all <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span>  <span class="token parameter variable">-u</span> wang <span class="token parameter variable">-a</span> <span class="token string">'ls /root'</span> <span class="token parameter variable">-b</span> --become-user<span class="token operator">=</span>root    <span class="token parameter variable">-k</span> <span class="token parameter variable">-K</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-3-3-ansible-playbook"><a href="#2-3-3-ansible-playbook" class="headerlink" title="2.3.3 ansible-playbook"></a>2.3.3 ansible-playbook</h5><p>此工具用于执行编写好的 playbook 任务</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible-playbook hello.yml
<span class="token function">cat</span>  hello.yml
---
<span class="token comment">#hello world yml file</span>
- hosts: websrvs
  remote_user: root
  tasks:
    - name: hello world
      command: /usr/bin/wall hello world<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-3-4-ansible-vault"><a href="#2-3-4-ansible-vault" class="headerlink" title="2.3.4 ansible-vault"></a>2.3.4 ansible-vault</h5><p>此工具可以用于加密解密 yml 文件</p>
<p>格式：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible-vault <span class="token punctuation">[</span>create<span class="token operator">|</span>decrypt<span class="token operator">|</span>edit<span class="token operator">|</span>encrypt<span class="token operator">|</span>rekey<span class="token operator">|</span>view<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>范例</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible-vault encrypt hello.yml   <span class="token comment"># 加密,加密后的文件是不能执行的，需要解密后执行</span>
ansible-vault decrypt hello.yml   <span class="token comment"># 解密</span>
ansible-vault view hello.yml      <span class="token comment"># 查看</span>
ansible-vault edit  hello.yml     <span class="token comment"># 编辑加密文件</span>
ansible-vault rekey  hello.yml    <span class="token comment"># 修改口令</span>
ansible-vault create new.yml      <span class="token comment"># 创建新文件</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-3-5-ansible-console"><a href="#2-3-5-ansible-console" class="headerlink" title="2.3.5 ansible-console"></a>2.3.5 ansible-console</h5><p>此工具可交互执行命令，支持 tab，ansible 2.0 + 新增</p>
<p>提示符格式：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">执行用户@当前操作的主机组 <span class="token punctuation">(</span>当前组的主机数量<span class="token punctuation">)</span><span class="token punctuation">[</span>f:并发数<span class="token punctuation">]</span>$<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>常用子命令：</p>
<ul>
<li>设置并发数：forks n 例如：forks 10</li>
<li>切换组：cd 主机组 例如：cd web</li>
<li>列出当前组主机列表：list</li>
<li>列出所有的内置命令：? 或 help</li>
</ul>
<p>范例</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible-console</span>
Welcome to the ansible console.
Type <span class="token builtin class-name">help</span> or ? to list commands.

root@all <span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ list
<span class="token number">10.0</span>.0.8
<span class="token number">10.0</span>.0.7
<span class="token number">10.0</span>.0.6
root@all <span class="token punctuation">(</span><span class="token number">3</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ <span class="token builtin class-name">cd</span> websrvs
root@websrvs <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ list
<span class="token number">10.0</span>.0.7
<span class="token number">10.0</span>.0.8
root@websrvs <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ forks <span class="token number">10</span>
root@websrvs <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:10<span class="token punctuation">]</span>$ <span class="token builtin class-name">cd</span> appsrvs
root@appsrvs <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ yum <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>present
root@appsrvs <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">[</span>f:5<span class="token punctuation">]</span>$ <span class="token function">service</span> <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-3-6-ansible-galaxy"><a href="#2-3-6-ansible-galaxy" class="headerlink" title="2.3.6 ansible-galaxy"></a>2.3.6 ansible-galaxy</h5><p>此工具会连接 <a target="_blank" rel="noopener" href="https://galaxy.ansible.com/">https://galaxy.ansible.com</a> 下载相应的 roles</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#列出所有已安装的galaxy</span>
ansible-galaxy list
<span class="token comment">#安装galaxy</span>
ansible-galaxy <span class="token function">install</span> geerlingguy.mysql
ansible-galaxy <span class="token function">install</span> geerlingguy.redis
<span class="token comment">#删除galaxy</span>
ansible-galaxy remove geerlingguy.redis<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="2-4-Ansible-常用模块"><a href="#2-4-Ansible-常用模块" class="headerlink" title="2.4 Ansible 常用模块"></a>2.4 Ansible 常用模块</h4><p>​        2015 年底 270 多个模块，2016 年达到 540 个，2018 年 01 月 12 日有 1378 个模块，2018 年 07 月 15 日 1852 个模块, 2019 年 05 月 25 日（ansible 2.7.10）时 2080 个模块，2020 年 03 月 02 日有 3387 个模块</p>
<p>虽然模块众多，但最常用的模块也就 2，30 个而已，针对特定业务只用 10 几个模块</p>
<p>常用模块帮助文档参考：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">https://docs.ansible.com/ansible/latest/modules/modules_by_category.html<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="2-4-1-Command-模块"><a href="#2-4-1-Command-模块" class="headerlink" title="2.4.1 Command 模块"></a>2.4.1 Command 模块</h5><p>功能：在远程主机执行命令，此为默认模块，可忽略 - m 选项</p>
<p>注意：此命令不支持 $VARNAME &lt; &gt; | ; &amp; 等，用 shell 模块实现</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs --list</span>
  hosts <span class="token punctuation">(</span><span class="token number">2</span><span class="token punctuation">)</span>:
    <span class="token number">10.10</span>.30.7
    <span class="token number">10.10</span>.30.8
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs -m command -a 'cat /etc/issue'</span>
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs -m command -a 'chdir=/etc cat issue'</span>
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># cd /etc ; cat issue^C</span>
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt cat issue'</span>
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs -m command -a 'chdir=/etc creates=/data/f1.txt cat issue'</span>
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> SUCCESS <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
skipped, since /data/f1.txt exists
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.
<span class="token punctuation">[</span>root@RHCE8 ~<span class="token punctuation">]</span><span class="token comment"># ansible websrvs -m command -a 'chdir=/etc removes=/data/f1.txt cat issue'</span>
<span class="token number">10.10</span>.30.8 <span class="token operator">|</span> SUCCESS <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
skipped, since /data/f1.txt does not exist
<span class="token number">10.10</span>.30.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

Welcome to SUSE Linux Enterprise Server <span class="token number">12</span> SP5  <span class="token punctuation">(</span>x86_64<span class="token punctuation">)</span> - Kernel <span class="token punctuation">\</span>r <span class="token punctuation">(</span><span class="token punctuation">\</span>l<span class="token punctuation">)</span>.

下面的这些都是有问题的
ansible websrvs <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span> <span class="token parameter variable">-a</span> ‘service vsftpd start’
ansible websrvs <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span> <span class="token parameter variable">-a</span> ‘echo magedu <span class="token operator">|</span><span class="token function">passwd</span> <span class="token parameter variable">--stdin</span> wang’
ansible websrvs <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span> <span class="token parameter variable">-a</span> <span class="token string">'rm -rf /data/'</span>
ansible websrvs <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span> <span class="token parameter variable">-a</span> <span class="token string">'echo hello > /data/hello.log'</span>
ansible websrvs <span class="token parameter variable">-m</span> <span class="token builtin class-name">command</span> <span class="token parameter variable">-a</span> <span class="token string">"echo <span class="token environment constant">$HOSTNAME</span>"</span>  <span class="token comment"># 有时可以</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-2-Shell-模块"><a href="#2-4-2-Shell-模块" class="headerlink" title="2.4.2 Shell 模块"></a>2.4.2 Shell 模块</h5><p>功能：和 command 相似，用 shell 执行命令</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a "echo $HOSTNAME"</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
ansible
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
ansible
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a 'echo $HOSTNAME'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
centos7.wangxiaochun.com
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
centos8.localdomain

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a 'echo centos | passwd --stdin wang'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
Changing password <span class="token keyword">for</span> user wang.
passwd: all authentication tokens updated successfully.
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
Changing password <span class="token keyword">for</span> user wang.
passwd: all authentication tokens updated successfully.
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a 'ls -l /etc/shadow'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
---------- <span class="token number">1</span> root root <span class="token number">889</span> Mar  <span class="token number">2</span> <span class="token number">14</span>:34 /etc/shadow
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
---------- <span class="token number">1</span> root root <span class="token number">944</span> Mar  <span class="token number">2</span> <span class="token number">14</span>:34 /etc/shadow
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a 'echo hello > /data/hello.log'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible websrvs -m shell -a 'cat  /data/hello.log'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
hello
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> CHANGED <span class="token operator">|</span> <span class="token assign-left variable">rc</span><span class="token operator">=</span><span class="token number">0</span> <span class="token operator">>></span>
hello<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>注意：调用 bash 执行命令 类似 cat &#x2F;tmp&#x2F;test.md | awk -F‘|’ ‘{print $1,$2}’ &amp;&gt; &#x2F;tmp&#x2F;example.txt 这些复杂命令，即使使用 shell 也可能会失败，解决办法：写到脚本时，copy 到远程，执行，再把需要的结果拉回执行命令的机器</p>
<p>范例：将 shell 模块代替 command，设为模块</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#vim /etc/ansible/ansible.cfg</span>
<span class="token comment">#修改下面一行</span>
module_name <span class="token operator">=</span> shell<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-3-Script-模块"><a href="#2-4-3-Script-模块" class="headerlink" title="2.4.3 Script 模块"></a>2.4.3 Script 模块</h5><p>功能：在远程主机上运行 ansible 服务器上的脚本</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible websrvs  <span class="token parameter variable">-m</span> script <span class="token parameter variable">-a</span> /data/test.sh<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="2-4-4-Copy-模块"><a href="#2-4-4-Copy-模块" class="headerlink" title="2.4.4 Copy 模块"></a>2.4.4 Copy 模块</h5><p>功能：从 ansible 服务器主控端复制文件到远程主机</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 如目标存在，默认覆盖，此处指定先备份</span>
ansible websrvs <span class="token parameter variable">-m</span> copy <span class="token parameter variable">-a</span> “src<span class="token operator">=</span>/root/test1.sh <span class="token assign-left variable">dest</span><span class="token operator">=</span>/tmp/test2.sh    <span class="token assign-left variable">owner</span><span class="token operator">=</span>wang  <span class="token assign-left variable">mode</span><span class="token operator">=</span><span class="token number">600</span> <span class="token assign-left variable">backup</span><span class="token operator">=</span>yes”
<span class="token comment"># 指定内容，直接生成目标文件</span>
ansible websrvs <span class="token parameter variable">-m</span> copy <span class="token parameter variable">-a</span> <span class="token string">"content='test line1<span class="token entity" title="\n">\n</span>test line2' dest=/tmp/test.txt"</span>
<span class="token comment"># 复制/etc/下的文件，不包括/etc/目录自身</span>
ansible websrvs <span class="token parameter variable">-m</span> copy <span class="token parameter variable">-a</span> “src<span class="token operator">=</span>/etc/ <span class="token assign-left variable">dest</span><span class="token operator">=</span>/backup”<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-5-Fetch-模块"><a href="#2-4-5-Fetch-模块" class="headerlink" title="2.4.5 Fetch 模块"></a>2.4.5 Fetch 模块</h5><p>功能：从远程主机提取文件至 ansible 的主控端，copy 相反，目前不支持目录</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible websrvs <span class="token parameter variable">-m</span> fetch <span class="token parameter variable">-a</span> ‘src<span class="token operator">=</span>/root/test.sh <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/scripts’<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible   all -m  fetch -a 'src=/etc/redhat-release dest=/data/os'  # 如果os目录不存在会创建</span>
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#tree /data/os/</span>
/data/os/
├── <span class="token number">10.0</span>.0.6
│   └── etc
│       └── redhat-release
├── <span class="token number">10.0</span>.0.7
│   └── etc
│       └── redhat-release
└── <span class="token number">10.0</span>.0.8
    └── etc
        └── redhat-release

<span class="token number">6</span> directories, <span class="token number">3</span> files<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-6-File-模块"><a href="#2-4-6-File-模块" class="headerlink" title="2.4.6 File 模块"></a>2.4.6 File 模块</h5><p>功能：设置文件属性</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#创建空文件</span>
ansible all <span class="token parameter variable">-m</span>  <span class="token function">file</span>  <span class="token parameter variable">-a</span> <span class="token string">'path=/data/test.txt state=touch'</span>
ansible all <span class="token parameter variable">-m</span>  <span class="token function">file</span>  <span class="token parameter variable">-a</span> <span class="token string">'path=/data/test.txt state=absent'</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">file</span> <span class="token parameter variable">-a</span> <span class="token string">"path=/root/test.sh owner=wang mode=755“
#创建目录
ansible all -m file -a "</span><span class="token assign-left variable">path</span><span class="token operator">=</span>/data/mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>directory <span class="token assign-left variable">owner</span><span class="token operator">=</span>mysql <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql"
<span class="token comment">#创建软链接</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">file</span> <span class="token parameter variable">-a</span> ‘src<span class="token operator">=</span>/data/testfile  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/testfile-link <span class="token assign-left variable">state</span><span class="token operator">=</span>link’<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-7-unarchive-模块"><a href="#2-4-7-unarchive-模块" class="headerlink" title="2.4.7 unarchive 模块"></a>2.4.7 unarchive 模块</h5><p>功能：解包解压缩</p>
<p>实现有两种用法：</p>
<p>1、将 ansible 主机上的压缩包传到远程主机后解压缩至特定目录，设置 copy&#x3D;yes </p>
<p>2、将远程主机上的某个压缩包解压缩到指定路径下，设置 copy&#x3D;no</p>
<p>常见参数：</p>
<ul>
<li>copy：默认为 yes，当 copy&#x3D;yes，拷贝的文件是从 ansible 主机复制到远程主机上，如果设置为 copy&#x3D;no，会在远程主机上寻找 src 源文件</li>
<li>remote_src：和 copy 功能一样且互斥，yes 表示在远程主机，不在 ansible 主机，no 表示文件在 ansible 主机上</li>
<li>src：源路径，可以是 ansible 主机上的路径，也可以是远程主机上的路径，如果是远程主机上的路径，则需要设置 copy&#x3D;no</li>
<li>dest：远程主机上的目标路径</li>
<li>mode：设置解压缩后的文件权限</li>
</ul>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all <span class="token parameter variable">-m</span> unarchive <span class="token parameter variable">-a</span> <span class="token string">'src=/data/foo.tgz dest=/var/lib/foo'</span>
ansible all <span class="token parameter variable">-m</span> unarchive <span class="token parameter variable">-a</span> <span class="token string">'src=/tmp/foo.zip dest=/data copy=no mode=0777'</span>
ansible all <span class="token parameter variable">-m</span> unarchive <span class="token parameter variable">-a</span> <span class="token string">'src=https://example.com/example.zip dest=/data copy=no'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-8-Archive-模块"><a href="#2-4-8-Archive-模块" class="headerlink" title="2.4.8 Archive 模块"></a>2.4.8 Archive 模块</h5><p>功能：打包压缩</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible websrvs <span class="token parameter variable">-m</span> archive  <span class="token parameter variable">-a</span> <span class="token string">'path=/var/log/ dest=/data/log.tar.bz2 format=bz2  owner=wang mode=0600'</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="2-4-9-Hostname-模块"><a href="#2-4-9-Hostname-模块" class="headerlink" title="2.4.9 Hostname 模块"></a>2.4.9 Hostname 模块</h5><p>功能：管理主机名</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible node1 <span class="token parameter variable">-m</span> <span class="token function">hostname</span> <span class="token parameter variable">-a</span> “name<span class="token operator">=</span>websrv”
ansible <span class="token number">192.168</span>.100.18 <span class="token parameter variable">-m</span> <span class="token function">hostname</span> <span class="token parameter variable">-a</span> <span class="token string">'name=node18.magedu.com'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h5 id="2-4-10-Cron-模块"><a href="#2-4-10-Cron-模块" class="headerlink" title="2.4.10 Cron 模块"></a>2.4.10 Cron 模块</h5><p>功能：计划任务 支持时间：minute，hour，day，month，weekday</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># 备份数据库脚本</span>
<span class="token punctuation">[</span>root@centos8 ~<span class="token punctuation">]</span><span class="token comment">#cat mysql_backup.sh</span>
mysqldump <span class="token parameter variable">-A</span> <span class="token parameter variable">-F</span> --single-transaction --master-data<span class="token operator">=</span><span class="token number">2</span> <span class="token parameter variable">-q</span> <span class="token parameter variable">-uroot</span> <span class="token operator">|</span><span class="token function">gzip</span> <span class="token operator">></span> /data/mysql_<span class="token variable"><span class="token variable">`</span><span class="token function">date</span> +%F_%T<span class="token variable">`</span></span>.sql.gz
<span class="token comment"># 创建任务</span>
ansible <span class="token number">10.0</span>.0.8 <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'</span>
ansible websrvs   <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">"minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &amp;>/dev/null' name=Synctime"</span>
<span class="token comment"># 禁用计划任务</span>
ansible websrvs   <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">"minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &amp;>/dev/null' name=Synctime disabled=yes"</span>
<span class="token comment"># 启用计划任务</span>
ansible websrvs   <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">"minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &amp;>/dev/null' name=Synctime disabled=no"</span>
<span class="token comment"># 删除任务</span>
ansible websrvs <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">"name='backup mysql' state=absent"</span>
ansible websrvs <span class="token parameter variable">-m</span> <span class="token function">cron</span> <span class="token parameter variable">-a</span> <span class="token string">'state=absent name=Synctime'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-11-Yum-模块"><a href="#2-4-11-Yum-模块" class="headerlink" title="2.4.11 Yum 模块"></a>2.4.11 Yum 模块</h5><p>功能：管理软件包，只支持 RHEL，CentOS，fedora，不支持 Ubuntu、suse 其它版本</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible websrvs <span class="token parameter variable">-m</span> yum <span class="token parameter variable">-a</span> ‘name<span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>present’  <span class="token comment">#安装</span>
ansible websrvs <span class="token parameter variable">-m</span> yum <span class="token parameter variable">-a</span> ‘name<span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>absent’  <span class="token comment">#删除</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h5 id="2-4-12-Service-模块"><a href="#2-4-12-Service-模块" class="headerlink" title="2.4.12 Service 模块"></a>2.4.12 Service 模块</h5><p>功能：管理服务</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all <span class="token parameter variable">-m</span> <span class="token function">service</span> <span class="token parameter variable">-a</span> <span class="token string">'name=httpd state=started enabled=yes'</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">service</span> <span class="token parameter variable">-a</span> <span class="token string">'name=httpd state=stopped'</span>
ansible all <span class="token parameter variable">-m</span> <span class="token function">service</span> <span class="token parameter variable">-a</span> <span class="token string">'name=httpd state=reloaded’
ansible all -m shell -a "sed -i '</span>s/^Listen <span class="token number">80</span>/Listen <span class="token number">8080</span>/<span class="token string">' /etc/httpd/conf/httpd.conf"
ansible all -m service -a '</span><span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>restarted'<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-13-User-模块"><a href="#2-4-13-User-模块" class="headerlink" title="2.4.13 User 模块"></a>2.4.13 User 模块</h5><p>功能：管理用户</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#创建用户</span>
ansible all <span class="token parameter variable">-m</span> user <span class="token parameter variable">-a</span> <span class="token string">'name=user1 comment=“test user” uid=2048 home=/app/user1 group=root'</span>

ansible all <span class="token parameter variable">-m</span> user <span class="token parameter variable">-a</span> <span class="token string">'name=nginx comment=nginx uid=88 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no  home=/data/nginx non_unique=yes'</span>

<span class="token comment">#删除用户及家目录等数据</span>
ansible all <span class="token parameter variable">-m</span> user <span class="token parameter variable">-a</span> <span class="token string">'name=nginx state=absent remove=yes'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-14-Group-模块"><a href="#2-4-14-Group-模块" class="headerlink" title="2.4.14 Group 模块"></a>2.4.14 Group 模块</h5><p>功能：管理组</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#创建组</span>
ansible websrvs <span class="token parameter variable">-m</span> group  <span class="token parameter variable">-a</span> <span class="token string">'name=nginx gid=88 system=yes'</span>
<span class="token comment">#删除组</span>
ansible websrvs <span class="token parameter variable">-m</span> group  <span class="token parameter variable">-a</span> <span class="token string">'name=nginx state=absent'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="2-4-15-Lineinfile-模块"><a href="#2-4-15-Lineinfile-模块" class="headerlink" title="2.4.15 Lineinfile 模块"></a>2.4.15 Lineinfile 模块</h5><p>ansible 在使用 sed 进行替换时，经常会遇到需要转义的问题，而且 ansible 在遇到特殊符号进行替换时，存在问题，无法正常进行替换 。其实在 ansible 自身提供了两个模块：lineinfile 模块和 replace 模块，可以方便的进行替换</p>
<p>功能：相当于 sed，可以修改文件内容</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all <span class="token parameter variable">-m</span>   lineinfile <span class="token parameter variable">-a</span> <span class="token string">"path=/etc/selinux/config regexp='^SELINUX=' line='SELINUX=enforcing'"</span>
ansible all <span class="token parameter variable">-m</span> lineinfile  <span class="token parameter variable">-a</span> <span class="token string">'dest=/etc/fstab state=absent regexp="^#"'</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h5 id="2-4-16-Replace-模块"><a href="#2-4-16-Replace-模块" class="headerlink" title="2.4.16 Replace 模块"></a>2.4.16 Replace 模块</h5><p>该模块有点类似于 sed 命令，主要也是基于正则进行匹配和替换</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all <span class="token parameter variable">-m</span> replace <span class="token parameter variable">-a</span> <span class="token string">"path=/etc/fstab regexp='^(UUID.*)' replace='#<span class="token entity" title="\1">\1</span>'"</span>  
ansible all <span class="token parameter variable">-m</span> replace <span class="token parameter variable">-a</span> <span class="token string">"path=/etc/fstab regexp='^#(.*)' replace='<span class="token entity" title="\1">\1</span>'"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<h5 id="2-4-17-Setup-模块"><a href="#2-4-17-Setup-模块" class="headerlink" title="2.4.17 Setup 模块"></a>2.4.17 Setup 模块</h5><p>功能：setup 模块来收集主机的系统信息，这些 facts 信息可以直接以变量的形式使用，但是如果主机较多，会影响执行速度，可以使用<code>gather_facts: no</code> 来禁止 Ansible 收集 facts 信息</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible all <span class="token parameter variable">-m</span> setup
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_nodename"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_hostname"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_domain"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_memtotal_mb"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_memory_mb"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_memfree_mb"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_os_family"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_distribution_major_version"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_distribution_version"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_processor_vcpus"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_all_ipv4_addresses"</span>
ansible all <span class="token parameter variable">-m</span> setup <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_architecture"</span>
ansible all <span class="token parameter variable">-m</span>  setup  <span class="token parameter variable">-a</span> <span class="token string">"filter=ansible_processor*"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible all  -m  setup -a 'filter=ansible_python_version'</span>
<span class="token number">10.0</span>.0.7 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"ansible_facts"</span><span class="token builtin class-name">:</span> <span class="token punctuation">&#123;</span>
        <span class="token string">"ansible_python_version"</span><span class="token builtin class-name">:</span> <span class="token string">"2.7.5"</span>,
        <span class="token string">"discovered_interpreter_python"</span><span class="token builtin class-name">:</span> <span class="token string">"/usr/bin/python"</span>
    <span class="token punctuation">&#125;</span>,
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> <span class="token boolean">false</span>
<span class="token punctuation">&#125;</span>
<span class="token number">10.0</span>.0.6 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"ansible_facts"</span><span class="token builtin class-name">:</span> <span class="token punctuation">&#123;</span>
        <span class="token string">"ansible_python_version"</span><span class="token builtin class-name">:</span> <span class="token string">"2.6.6"</span>,
        <span class="token string">"discovered_interpreter_python"</span><span class="token builtin class-name">:</span> <span class="token string">"/usr/bin/python"</span>
    <span class="token punctuation">&#125;</span>,
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> <span class="token boolean">false</span>
<span class="token punctuation">&#125;</span>
<span class="token number">10.0</span>.0.8 <span class="token operator">|</span> SUCCESS <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">&#123;</span>
    <span class="token string">"ansible_facts"</span><span class="token builtin class-name">:</span> <span class="token punctuation">&#123;</span>
        <span class="token string">"ansible_python_version"</span><span class="token builtin class-name">:</span> <span class="token string">"3.6.8"</span>,
        <span class="token string">"discovered_interpreter_python"</span><span class="token builtin class-name">:</span> <span class="token string">"/usr/libexec/platform-python"</span>
    <span class="token punctuation">&#125;</span>,
    <span class="token string">"changed"</span><span class="token builtin class-name">:</span> <span class="token boolean">false</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="三、Playbook"><a href="#三、Playbook" class="headerlink" title="三、Playbook"></a>三、Playbook</h3><h4 id="3-1-playbook-介绍"><a href="#3-1-playbook-介绍" class="headerlink" title="3.1 playbook 介绍"></a>3.1 playbook 介绍</h4><p><img src="https://gitee.com/miaohsukang/myblog/raw/master/img/ansible-playbook.png"></p>
<p>playbooks 是一个不同于使用Ansible命令行执行方式的模式，其功能更强大灵活。简单来说，playbook是一个非常简单的配置管理和多主机部署系统，不同于任何已经存在的模式，可作为一个适合部署复杂应用程序的基础。Playbook可以定制配置，可以按照指定的操作步骤有序执行，支持同步和异步方式。值得注意的是playbook是通过YAML格式来进行描述定义的。</p>
<p>Playbook 剧本是由一个或多个 “play” 组成的列表。</p>
<p>Play 的主要功能在于将预定义的一组主机，装扮成事先通过 ansible 中的 task 定义好的角色。Task 实际是调用 Ansible 的一个 module，将多个 play 组织在一个 playbook 中，即可以让它们联合起来，按事先编排的机制执行预定义的动作</p>
<p>Playbook 文件是采用 YAML 语言编写的。</p>
<h4 id="3-2-YAML-语言"><a href="#3-2-YAML-语言" class="headerlink" title="3.2 YAML 语言"></a>3.2 YAML 语言</h4><h5 id="3-2-1-YAMl-语言介绍"><a href="#3-2-1-YAMl-语言介绍" class="headerlink" title="3.2.1 YAMl 语言介绍"></a>3.2.1 YAMl 语言介绍</h5><p>​         YAML 是一个可读性高的用来表达资料序列的格式。YAML 参考了其他多种语言，包括：XML、C 语言、Python、Perl 以及电子邮件格式 RFC2822 等。Clark Evans 在 2001 年首次发表了这种语言，另外 Ingy döt Net 与 Oren Ben-Kiki 也是这语言的共同设计者, 目前很多软件中采有此格式的文件，如: ubuntu，anisble，docker，k8s 等 YAML：YAML Ain’t Markup Language，即 YAML 不是 XML。不过，在开发的这种语言时，YAML 的意思其实是：”Yet Another Markup Language”（仍是一种标记语言）</p>
<p>YAML 官方网站：<a target="_blank" rel="noopener" href="http://www.yaml.org/">http://www.yaml.org</a></p>
<h5 id="3-2-2-YAML-语言特性"><a href="#3-2-2-YAML-语言特性" class="headerlink" title="3.2.2 YAML 语言特性"></a>3.2.2 YAML 语言特性</h5><ul>
<li>YAML 的可读性好</li>
<li>YAML 和脚本语言的交互性好</li>
<li>YAML 使用实现语言的数据类型</li>
<li>YAML 有一个一致的信息模型</li>
<li>YAML 易于实现</li>
<li>YAML 可以基于流来处理</li>
<li>YAML 表达能力强，扩展性好</li>
</ul>
<h5 id="3-2-3-YAML-语法简介"><a href="#3-2-3-YAML-语法简介" class="headerlink" title="3.2.3 YAML 语法简介"></a>3.2.3 YAML 语法简介</h5><ul>
<li>在单一文件第一行，用连续三个连字号 “-” 开始，还有选择性的连续三个点号( … ) 用来表示文件的结尾</li>
<li>次行开始正常写 Playbook 的内容，一般建议写明该 Playbook 的功能</li>
<li>使用 #号注释代码</li>
<li>缩进必须是统一的，不能空格和 tab 混用</li>
<li>缩进的级别也必须是一致的，同样的缩进代表同样的级别，程序判别配置的级别是通过缩进结合换行来实现的 YAML 文件内容是区别大小写的，key&#x2F;value 的值均需大小写敏感</li>
<li>多个 key&#x2F;value 可同行写也可换行写，同行使用，分隔</li>
<li>value 可是个字符串，也可是另一个列表</li>
<li>一个完整的代码块功能需最少元素需包括 name 和 task</li>
<li>一个 name 只能包括一个 task</li>
<li>YAML 文件扩展名通常为 yml 或 yaml</li>
</ul>
<p>YAML 的语法和其他高阶语言类似，并且可以简单表达清单、散列表、标量等数据结构。其结构（Structure）通过空格来展示，序列（Sequence）里的项用 “-“ 来代表，Map 里的键值对用 “:” 分隔，下面介绍常见的数据结构。</p>
<h6 id="3-2-3-1-List-列表"><a href="#3-2-3-1-List-列表" class="headerlink" title="3.2.3.1 List 列表"></a>3.2.3.1 List 列表</h6><p>列表由多个元素组成，每个元素放在不同行，且元素前均使用 “-” 打头，或者将所有元素用 [ ] 括起来放在同一行 范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># A list of tasty fruits，注意-号后面有一个空格</span>
- Apple
- Orange
- Strawberry
- Mango

<span class="token punctuation">[</span>Apple,Orange,Strawberry,Mango<span class="token punctuation">]</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h6 id="3-2-3-2-Dictionary-字典"><a href="#3-2-3-2-Dictionary-字典" class="headerlink" title="3.2.3.2 Dictionary 字典"></a>3.2.3.2 Dictionary 字典</h6><p>字典由多个 key 与 value 构成，key 和 value 之间用冒号 ：分隔，所有 k&#x2F;v 可以放在一行，或者每个 k&#x2F;v 分别放在不同行</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment"># An employee record</span>
name: Example Developer
job: Developer
skill: Elite
也可以将key:value放置于<span class="token punctuation">&#123;</span><span class="token punctuation">&#125;</span>中进行表示，用,分隔多个key:value

<span class="token comment"># An employee record，注意下面冒号后面有一个空格</span>
<span class="token punctuation">&#123;</span>name: “Example Developer”, job: “Developer”, skill: “Elite”<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">name: John Smith
age: <span class="token number">41</span>
gender: Male
spouse:
  name: Jane Smith
  age: <span class="token number">37</span>
  gender: Female
children:
  - name: Jimmy Smith
    age: <span class="token number">17</span>
    gender: Male
  - name: Jenny Smith
    age <span class="token number">13</span>
    gender: Female<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>列表和字典是可以互相嵌套的</p>
<h5 id="3-2-4-三种常见的数据格式"><a href="#3-2-4-三种常见的数据格式" class="headerlink" title="3.2.4 三种常见的数据格式"></a>3.2.4 三种常见的数据格式</h5><ul>
<li>XML：Extensible Markup Language，可扩展标记语言，可用于数据交换和配置</li>
<li>JSON：JavaScript Object Notation, JavaScript 对象表记法，主要用来数据交换或配置，不支持注释</li>
<li>YAML：YAML Ain’t Markup Language YAML 不是一种标记语言， 主要用来配置，大小写敏感，不支持 tab</li>
</ul>
<p><strong>可以用工具互相转换，参考网站：</strong></p>
<p><a target="_blank" rel="noopener" href="https://www.json2yaml.com/">https://www.json2yaml.com/</a></p>
<p><a target="_blank" rel="noopener" href="http://www.bejson.com/json/json2yaml/">http://www.bejson.com/json/json2yaml/</a></p>
<h4 id="3-3-Playbook-核心元素"><a href="#3-3-Playbook-核心元素" class="headerlink" title="3.3 Playbook 核心元素"></a>3.3 Playbook 核心元素</h4><ul>
<li>Hosts 执行的远程主机列表</li>
<li>Tasks 任务集</li>
<li>Variables 内置变量或自定义变量在 playbook 中调用</li>
<li>Templates 模板，可替换模板文件中的变量并实现一些简单逻辑的文件</li>
<li>Handlers 和 notify 结合使用，由特定条件触发的操作，满足条件方才执行，否则不执行</li>
<li>tags 标签 指定某条任务执行，用于选择运行 playbook 中的部分代码。ansible 具有幂等性，因此会自动跳过没有变化的部分，即便如此，有些代码为测试其确实没有发生变化的时间依然会非常地长。此时，如果确信其没有变化，就可以通过 tags 跳过此些代码片断</li>
</ul>
<h5 id="3-3-1-hosts-组件"><a href="#3-3-1-hosts-组件" class="headerlink" title="3.3.1 hosts 组件"></a>3.3.1 hosts 组件</h5><p>Hosts：playbook 中的每一个 play 的目的都是为了让特定主机以某个指定的用户身份执行任务。hosts 用于指定要执行指定任务的主机，须事先定义在主机清单中</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">one.example.com
one.example.com:two.example.com
<span class="token number">192.168</span>.1.50
<span class="token number">192.168</span>.1.*
Websrvs:dbsrvs         <span class="token comment">#或者，两个组的并集</span>
Websrvs:<span class="token operator">&amp;</span>dbsrvs        <span class="token comment">#与，两个组的交集</span>
webservers:<span class="token operator">!</span>phoenix  <span class="token comment">#在websrvs组，但不在dbsrvs组</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>案例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">- hosts: websrvs:appsrvs<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<h5 id="3-3-2-remote-user-组件"><a href="#3-3-2-remote-user-组件" class="headerlink" title="3.3.2 remote_user 组件"></a>3.3.2 remote_user 组件</h5><p>remote_user: 可用于 Host 和 task 中。也可以通过指定其通过 sudo 的方式在远程主机上执行任务，其可用于 play 全局或某任务；此外，甚至可以在 sudo 时使用 sudo_user 指定 sudo 时切换的用户</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token builtin class-name">test</span> connection
      ping:
      remote_user: magedu
      sudo: <span class="token function">yes</span>              <span class="token comment"># 默认sudo为root</span>
      sudo_user:wang         <span class="token comment"># sudo为wang</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-3-3-task-列表和-action-组件"><a href="#3-3-3-task-列表和-action-组件" class="headerlink" title="3.3.3 task 列表和 action 组件"></a>3.3.3 task 列表和 action 组件</h5><p>play 的主体部分是 task list，task list 中有一个或多个 task, 各个 task 按次序逐个在 hosts 中指定的所有主机上执行，即在所有主机上完成第一个 task 后，再开始第二个 task task 的目的是使用指定的参数执行模块，而在模块参数中可以使用变量。模块执行是幂等的，这意味着多次执行是安全的，因为其结果均一致 每个 task 都应该有其 name，用于 playbook 的执行结果输出，建议其内容能清晰地描述任务执行步骤。如果未提供 name，则 action 的结果将用于输出</p>
<p>task 两种格式： (1) action: module arguments (2) module: arguments 建议使用</p>
<p>注意：shell 和 command 模块后面跟命令，而非 key&#x3D;value</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: <span class="token function">install</span> httpd
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd
    - name: start httpd
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-3-4-其它组件"><a href="#3-3-4-其它组件" class="headerlink" title="3.3.4 其它组件"></a>3.3.4 其它组件</h5><p>某任务的状态在运行后为 changed 时，可通过 “notify” 通知给相应的 handlers 任务可以通过 “tags“打标签，可在 ansible-playbook 命令上使用 - t 指定进行调用</p>
<h5 id="4-3-5-ShellScripts-VS-Playbook-案例"><a href="#4-3-5-ShellScripts-VS-Playbook-案例" class="headerlink" title="4.3.5 ShellScripts VS Playbook 案例"></a><strong>4.3.5 ShellScripts VS Playbook 案例</strong></h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#SHELL脚本实现</span>
<span class="token comment">#!/bin/bash</span>
<span class="token comment"># 安装Apache</span>
yum <span class="token function">install</span> <span class="token parameter variable">--quiet</span> <span class="token parameter variable">-y</span> httpd
<span class="token comment"># 复制配置文件</span>
<span class="token function">cp</span> /tmp/httpd.conf /etc/httpd/conf/httpd.conf
cp/tmp/vhosts.conf /etc/httpd/conf.d/
<span class="token comment"># 启动Apache，并设置开机启动</span>
systemctl <span class="token builtin class-name">enable</span> <span class="token parameter variable">--now</span> httpd

<span class="token comment">#Playbook实现</span>
---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: <span class="token string">"安装Apache"</span>
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd
    - name: <span class="token string">"复制配置文件"</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>/tmp/httpd.conf <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/httpd/conf/
    - name: <span class="token string">"复制配置文件"</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>/tmp/vhosts.conf <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/httpd/conf.d/
    - name: <span class="token string">"启动Apache，并设置开机启动"</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-4-playbook-命令"><a href="#3-4-playbook-命令" class="headerlink" title="3.4 playbook 命令"></a><strong>3.4</strong> playbook 命令</h4><p>格式</p>
<pre class="line-numbers language-none"><code class="language-none">ansible-playbook &lt;filename.yml&gt; ... [options]<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>常见选项</p>
<pre class="line-numbers language-none"><code class="language-none">-C --check             #只检测可能会发生的改变，但不真正执行操作
--list-hosts         #列出运行任务的主机
--list-tags            #列出tag
--list-tasks        #列出task
--limit 主机列表       #只针对主机列表中的主机执行
-v -vv  -vvv        #显示过程<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例</p>
<pre class="line-numbers language-none"><code class="language-none">ansible-playbook  file.yml  --check #只检测
ansible-playbook  file.yml
ansible-playbook  file.yml  --limit websrvs<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h4 id="3-5-Playbook-初步"><a href="#3-5-Playbook-初步" class="headerlink" title="3.5 Playbook 初步"></a>3.5 Playbook 初步</h4><h5 id="3-5-1-利用-playbook-创建-mysql-用户"><a href="#3-5-1-利用-playbook-创建-mysql-用户" class="headerlink" title="3.5.1 利用 playbook 创建 mysql 用户"></a><strong>3.5.1</strong> 利用 playbook 创建 mysql 用户</h5><p>范例：mysql_user.yml</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: dbsrvs
  remote_user: root
  gather_facts: no
  
  tasks:
    - <span class="token punctuation">&#123;</span>name: create group, group: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">system</span><span class="token operator">=</span>yes <span class="token assign-left variable">gid</span><span class="token operator">=</span><span class="token number">306</span><span class="token punctuation">&#125;</span>
    - name: create user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">shell</span><span class="token operator">=</span>/sbin/nologin <span class="token assign-left variable">system</span><span class="token operator">=</span>yes <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql <span class="token assign-left variable">uid</span><span class="token operator">=</span><span class="token number">306</span> <span class="token assign-left variable">home</span><span class="token operator">=</span>/data/mysql <span class="token assign-left variable">create_home</span><span class="token operator">=</span>no<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-5-2-利用-playbook-安装-nginx"><a href="#3-5-2-利用-playbook-安装-nginx" class="headerlink" title="3.5.2 利用 playbook 安装 nginx"></a><strong>3.5.2</strong> 利用 playbook 安装 nginx</h5><p>范例：install_nginx.yml</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
<span class="token comment"># install nginx</span>
- hosts: websrvs
  remote_user: root
  gather_facts: no
  
  tasks:
    - name: <span class="token function">add</span> group nginx
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: <span class="token function">add</span> user nginx
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">group</span><span class="token operator">=</span>nginx
    - name: Install Nginx
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: web page
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>files/index.html <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/share/nginx/html/index.html
    - name: Start Nginx
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-5-3-利用-playbook-安装和卸载-httpd"><a href="#3-5-3-利用-playbook-安装和卸载-httpd" class="headerlink" title="3.5.3 利用 playbook 安装和卸载 httpd"></a>3.5.3 利用 playbook 安装和卸载 httpd</h5><p>范例：install_httpd.yml</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
<span class="token comment">#install httpd</span>
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: Install httpd
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: Install configure <span class="token function">file</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>files/httpd.conf <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/httpd/conf/
    - name: web html
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>files/index.html  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/var/www/html/
    - name: start <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes

ansible-playbook   install_httpd.yml <span class="token parameter variable">--limit</span> <span class="token number">10.0</span>.0.8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：remove_httpd.yml</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#remove_httpd.yml</span>
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: remove httpd package
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>absent
    - name: remove apache user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>apache <span class="token assign-left variable">state</span><span class="token operator">=</span>absent
    - name: remove config <span class="token function">file</span>
      file: <span class="token assign-left variable">name</span><span class="token operator">=</span>/etc/httpd  <span class="token assign-left variable">state</span><span class="token operator">=</span>absent
    - name: remove web html
      file: <span class="token assign-left variable">name</span><span class="token operator">=</span>/var/www/html/index.html <span class="token assign-left variable">state</span><span class="token operator">=</span>absent<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-5-4-利用-playbook-安装-mysql"><a href="#3-5-4-利用-playbook-安装-mysql" class="headerlink" title="3.5.4 利用 playbook 安装 mysql"></a>3.5.4 利用 playbook 安装 mysql</h5><p>范例：安装 mysql-5.6.46-linux-glibc2.12</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ls -l /data/ansible/files/mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz</span>
-rw-r--r-- <span class="token number">1</span> root root <span class="token number">403177622</span> Dec  <span class="token number">4</span> <span class="token number">13</span>:05 /data/ansible/files/mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/files/my.cnf</span>
<span class="token punctuation">[</span>mysqld<span class="token punctuation">]</span>
<span class="token assign-left variable">socket</span><span class="token operator">=</span>/tmp/mysql.sock
<span class="token assign-left variable">user</span><span class="token operator">=</span>mysql
symbolic-links<span class="token operator">=</span><span class="token number">0</span>
<span class="token assign-left variable">datadir</span><span class="token operator">=</span>/data/mysql
<span class="token assign-left variable">innodb_file_per_table</span><span class="token operator">=</span><span class="token number">1</span>
log-bin
pid-file<span class="token operator">=</span>/data/mysql/mysqld.pid

<span class="token punctuation">[</span>client<span class="token punctuation">]</span>
<span class="token assign-left variable">port</span><span class="token operator">=</span><span class="token number">3306</span>
<span class="token assign-left variable">socket</span><span class="token operator">=</span>/tmp/mysql.sock

<span class="token punctuation">[</span>mysqld_safe<span class="token punctuation">]</span>
log-error<span class="token operator">=</span>/var/log/mysqld.log

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/files/secure_mysql.sh</span>
<span class="token comment">#!/bin/bash</span>
/usr/local/mysql/bin/mysql_secure_installation <span class="token operator">&lt;&lt;</span><span class="token string">EOF

y
magedu
magedu
y
y
y
y
EOF</span>


<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#tree /data/ansible/files/</span>
/data/ansible/files/
├── my.cnf
├── mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz
└── secure_mysql.sh

<span class="token number">0</span> directories, <span class="token number">3</span> files



<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/install_mysql.yml</span>
---
<span class="token comment"># install mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz</span>
- hosts: dbsrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: <span class="token function">install</span> packages
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>libaio,perl-Data-Dumper,perl-Getopt-Long
    - name: create mysql group
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">gid</span><span class="token operator">=</span><span class="token number">306</span> 
    - name: create mysql user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">uid</span><span class="token operator">=</span><span class="token number">306</span> <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql <span class="token assign-left variable">shell</span><span class="token operator">=</span>/sbin/nologin <span class="token assign-left variable">system</span><span class="token operator">=</span>yes <span class="token assign-left variable">create_home</span><span class="token operator">=</span>no <span class="token assign-left variable">home</span><span class="token operator">=</span>/data/mysql
    - name: copy <span class="token function">tar</span> to remote <span class="token function">host</span> and <span class="token function">file</span> mode
      unarchive: <span class="token assign-left variable">src</span><span class="token operator">=</span>/data/ansible/files/mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/local/ <span class="token assign-left variable">owner</span><span class="token operator">=</span>root <span class="token assign-left variable">group</span><span class="token operator">=</span>root
    - name: create linkfile  /usr/local/mysql
      file: <span class="token assign-left variable">src</span><span class="token operator">=</span>/usr/local/mysql-5.6.46-linux-glibc2.12-x86_64 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/local/mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>link
    - name: data <span class="token function">dir</span>
      shell: <span class="token assign-left variable">chdir</span><span class="token operator">=</span>/usr/local/mysql/  ./scripts/mysql_install_db <span class="token parameter variable">--datadir</span><span class="token operator">=</span>/data/mysql <span class="token parameter variable">--user</span><span class="token operator">=</span>mysql
      tags: data
    - name: config my.cnf
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>/data/ansible/files/my.cnf  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/my.cnf
    - name: <span class="token function">service</span> script
      shell: /bin/cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld
    - name: <span class="token builtin class-name">enable</span> <span class="token function">service</span>
      shell: /etc/init.d/mysqld start<span class="token punctuation">;</span><span class="token function">chkconfig</span> <span class="token parameter variable">--add</span> mysqld<span class="token punctuation">;</span><span class="token function">chkconfig</span> mysqld on
      tags: <span class="token function">service</span>
    - name: <span class="token environment constant">PATH</span> variable
      copy: <span class="token assign-left variable">content</span><span class="token operator">=</span><span class="token string">'PATH=/usr/local/mysql/bin:$PATH'</span> <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/profile.d/mysql.sh
    - name: secure script
      script: /data/ansible/files/secure_mysql.sh
      tags: script<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>范例：install_mariadb.yml</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
<span class="token comment">#Installing MariaDB Binary Tarballs</span>
- hosts: dbsrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: create group
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">gid</span><span class="token operator">=</span><span class="token number">27</span> <span class="token assign-left variable">system</span><span class="token operator">=</span>yes
    - name: create user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">uid</span><span class="token operator">=</span><span class="token number">27</span> <span class="token assign-left variable">system</span><span class="token operator">=</span>yes <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql <span class="token assign-left variable">shell</span><span class="token operator">=</span>/sbin/nologin <span class="token assign-left variable">home</span><span class="token operator">=</span>/data/mysql <span class="token assign-left variable">create_home</span><span class="token operator">=</span>no
    - name: <span class="token function">mkdir</span> datadir
      file: <span class="token assign-left variable">path</span><span class="token operator">=</span>/data/mysql <span class="token assign-left variable">owner</span><span class="token operator">=</span>mysql <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>directory
    - name: unarchive package
      unarchive: <span class="token assign-left variable">src</span><span class="token operator">=</span>/data/ansible/files/mariadb-10.2.27-linux-x86_64.tar.gz <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/local/ <span class="token assign-left variable">owner</span><span class="token operator">=</span>root <span class="token assign-left variable">group</span><span class="token operator">=</span>root
    - name: <span class="token function">link</span>
      file: <span class="token assign-left variable">src</span><span class="token operator">=</span>/usr/local/mariadb-10.2.27-linux-x86_64 <span class="token assign-left variable">path</span><span class="token operator">=</span>/usr/local/mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>link
    - name: <span class="token function">install</span> database
      shell: <span class="token assign-left variable">chdir</span><span class="token operator">=</span>/usr/local/mysql   ./scripts/mysql_install_db <span class="token parameter variable">--datadir</span><span class="token operator">=</span>/data/mysql <span class="token parameter variable">--user</span><span class="token operator">=</span>mysql
    - name: config <span class="token function">file</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>/data/ansible/files/my.cnf  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/ <span class="token assign-left variable">backup</span><span class="token operator">=</span>yes
    - name: <span class="token function">service</span> script
      shell: /bin/cp  /usr/local/mysql/support-files/mysql.server  /etc/init.d/mysqld
    - name: start <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysqld <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes
    - name: <span class="token environment constant">PATH</span> variable
      copy: <span class="token assign-left variable">content</span><span class="token operator">=</span><span class="token string">'PATH=/usr/local/mysql/bin:$PATH'</span> <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/profile.d/mysql.sh<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-6-Playbook-中使用-handlers-和-notify"><a href="#3-6-Playbook-中使用-handlers-和-notify" class="headerlink" title="3.6 Playbook 中使用 handlers 和 notify"></a><strong>3.6</strong> Playbook 中使用 handlers 和 notify</h4><p>Handlers 本质是 task list ，类似于 MySQL 中的触发器触发的行为，其中的 task 与前述的 task 并没有本质上的不同，主要用于当关注的资源发生变化时，才会采取一定的操作。而 Notify 对应的 action 可用于在每个 play 的最后被触发，这样可避免多次有改变发生时每次都执行指定的操作，仅在所有的变化发生完成后一次性地执行指定操作。在 notify 中列出的操作称为 handler，也即 notify 中调用 handler 中定义的操作</p>
<p>案例:</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  gather_facts: no
  tasks:
    - name: Install httpd
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: Install configure <span class="token function">file</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>files/httpd.conf <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/httpd/conf/
      notify: restart httpd
    - name: ensure apache is running
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes

  handlers:
    - name: restart httpd
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>restarted<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>案例:</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: <span class="token function">add</span> group nginx
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: <span class="token function">add</span> user nginx
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">group</span><span class="token operator">=</span>nginx
    - name: Install Nginx
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: config
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>/root/config.txt <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf
      notify:
        - Restart Nginx
        - Check Nginx Process

   handlers:
     - name: Restart Nginx
       service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>restarted <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes
     - name: Check Nginx process
       shell: <span class="token function">killall</span> <span class="token parameter variable">-0</span> nginx <span class="token operator">&amp;></span> /tmp/nginx.log<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-7-Playbook-中使用-tags-组件"><a href="#3-7-Playbook-中使用-tags-组件" class="headerlink" title="3.7 Playbook 中使用 tags 组件"></a>3.7 Playbook 中使用 tags 组件</h4><p>在 playbook 文件中，可以利用 tags 组件，为特定 task 指定标签，当在执行 playbook 时，可以只执行特定 tags 的 task, 而非整个 playbook 文件</p>
<p>案例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span>  httpd.yml
---
<span class="token comment"># tags example</span>
- hosts: websrvs
  remote_user: root
  gather_facts: no

  tasks:
    - name: Install httpd
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: Install configure <span class="token function">file</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>files/httpd.conf <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/httpd/conf/
      tags: conf
    - name: start httpd <span class="token function">service</span>
      tags: <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>httpd <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes

ansible-playbook –t conf,service  httpd.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-8-Playbook-中使用变量"><a href="#3-8-Playbook-中使用变量" class="headerlink" title="3.8 Playbook 中使用变量"></a>3.8 Playbook 中使用变量</h4><p>变量名：仅能由字母、数字和下划线组成，且只能以字母开头</p>
<p>变量定义：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token assign-left variable">variable</span><span class="token operator">=</span>value<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token assign-left variable">http_port</span><span class="token operator">=</span><span class="token number">80</span><span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>

<p>变量调用方式：</p>
<p>通过  调用变量，且变量名前后建议加空格，有时用“” 才生效</p>
<p>变量来源：</p>
<ol>
<li><p>ansible 的 setup facts 远程主机的所有变量都可直接调用</p>
</li>
<li><p>通过命令行指定变量，优先级最高</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">ansible-playbook <span class="token parameter variable">-e</span> <span class="token assign-left variable">varname</span><span class="token operator">=</span>value<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</li>
<li><p>在 playbook 文件中定义</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">vars:
  - var1: value1
  - var2: value2<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>在独立的变量 YAML 文件中定义</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">- hosts: all
  vars_files:
    - vars.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>
</li>
<li><p>在 &#x2F;etc&#x2F;ansible&#x2F;hosts 中定义</p>
<p>主机（普通）变量：主机组中主机单独定义，优先级高于公共变量 组（公共）变量：针对主机组中所有主机定义统一变量</p>
</li>
<li><p>在 role 中定义</p>
</li>
</ol>
<h5 id="3-8-1-使用-setup-模块中变量"><a href="#3-8-1-使用-setup-模块中变量" class="headerlink" title="3.8.1 使用 setup 模块中变量"></a>3.8.1 使用 setup 模块中变量</h5><p>本模块自动在 playbook 调用，不要用 ansible 命令调用</p>
<p>案例：使用 setup 变量</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
<span class="token comment">#var.yml</span>
- hosts: all
  remote_user: root
  gather_facts: <span class="token function">yes</span>

  tasks:
    - name: create log <span class="token function">file</span>
      file: <span class="token assign-left variable">name</span><span class="token operator">=</span>/data/<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> ansible_nodename <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>.log <span class="token assign-left variable">state</span><span class="token operator">=</span>touch <span class="token assign-left variable">owner</span><span class="token operator">=</span>wang <span class="token assign-left variable">mode</span><span class="token operator">=</span><span class="token number">600</span>


ansible-playbook  var.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-8-2-在-playbook-命令行中定义变量"><a href="#3-8-2-在-playbook-命令行中定义变量" class="headerlink" title="3.8.2 在 playbook 命令行中定义变量"></a>3.8.2 在 playbook 命令行中定义变量</h5><p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> var2.yml
---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: <span class="token function">install</span> package
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> pkname <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present

ansible-playbook  –e <span class="token assign-left variable">pkname</span><span class="token operator">=</span>httpd  var2.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-8-3-在-playbook-文件中定义变量"><a href="#3-8-3-在-playbook-文件中定义变量" class="headerlink" title="3.8.3 在 playbook 文件中定义变量"></a>3.8.3 在 playbook 文件中定义变量</h5><p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> var3.yml
---
- hosts: websrvs
  remote_user: root
  vars:
    - username: user1
    - groupname: group1

  tasks:
    - name: create group
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> groupname <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: create user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> username <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">group</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> groupname <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present

ansible-playbook <span class="token parameter variable">-e</span> "username<span class="token operator">=</span>user2 <span class="token assign-left variable">groupname</span><span class="token operator">=</span>group2”  var3.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-6-4-使用变量文件"><a href="#3-6-4-使用变量文件" class="headerlink" title="3.6.4 使用变量文件"></a>3.6.4 使用变量文件</h5><p>可以在一个独立的 playbook 文件中定义变量，在另一个 playbook 文件中引用变量文件中的变量，比 playbook 中定义的变量优化级高</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> vars.yml
---
<span class="token comment"># variables file</span>
package_name: mariadb-server
service_name: mariadb


<span class="token function">vim</span>  var4.yml
---
<span class="token comment">#install package and start service</span>
- hosts: dbsrvs
  remote_user: root
  vars_files:
    - /root/vars.yml

  tasks:
    - name: <span class="token function">install</span> package
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> package_name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
      tags: <span class="token function">install</span>
    - name: start <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> service_name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">cat</span>  vars2.yml
---
var1: httpd
var2: nginx

<span class="token function">cat</span>  var5.yml
---
- hosts: web
  remote_user: root
  vars_files:
    - vars2.yml

   tasks:
     - name: create httpd log
       file: <span class="token assign-left variable">name</span><span class="token operator">=</span>/app/<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> var1 <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>.log <span class="token assign-left variable">state</span><span class="token operator">=</span>touch
     - name: create nginx log
       file: <span class="token assign-left variable">name</span><span class="token operator">=</span>/app/<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> var2 <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>.log <span class="token assign-left variable">state</span><span class="token operator">=</span>touch<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-6-5-主机清单文件中定义变量"><a href="#3-6-5-主机清单文件中定义变量" class="headerlink" title="3.6.5 主机清单文件中定义变量"></a>3.6.5 主机清单文件中定义变量</h5><h6 id="3-6-5-1-主机变量"><a href="#3-6-5-1-主机变量" class="headerlink" title="3.6.5.1 主机变量"></a>3.6.5.1 主机变量</h6><p>在 inventory 主机清单文件中为指定的主机定义变量以便于在 playbook 中使用</p>
<p>范例：</p>
<pre class="line-numbers language-none"><code class="language-none">[websrvs]
www1.magedu.com http_port&#x3D;80 maxRequestsPerChild&#x3D;808
www2.magedu.com http_port&#x3D;8080 maxRequestsPerChild&#x3D;909<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h6 id="3-6-5-2-组（公共）变量"><a href="#3-6-5-2-组（公共）变量" class="headerlink" title="3.6.5.2 组（公共）变量"></a>3.6.5.2 组（公共）变量</h6><p>在 inventory 主机清单文件中赋予给指定组内所有主机上的在 playbook 中可用的变量，如果和主机变量是同名，优先级低于主机变量</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>websrvs<span class="token punctuation">]</span>
www1.magedu.com
www2.magedu.com

<span class="token punctuation">[</span>websrvs:vars<span class="token punctuation">]</span>
<span class="token assign-left variable">ntp_server</span><span class="token operator">=</span>ntp.magedu.com
<span class="token assign-left variable">nfs_server</span><span class="token operator">=</span>nfs.magedu.com<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> /etc/ansible/hosts

<span class="token punctuation">[</span>websrvs<span class="token punctuation">]</span>
<span class="token number">192.168</span>.0.101 <span class="token assign-left variable">hname</span><span class="token operator">=</span>www1 <span class="token assign-left variable">domain</span><span class="token operator">=</span>magedu.io
<span class="token number">192.168</span>.0.102 <span class="token assign-left variable">hname</span><span class="token operator">=</span>www2

<span class="token punctuation">[</span>websvrs:vars<span class="token punctuation">]</span>
<span class="token assign-left variable">mark</span><span class="token operator">=</span>“-”
<span class="token assign-left variable">domain</span><span class="token operator">=</span>magedu.org


ansible  websvrs  –m <span class="token function">hostname</span> –a ‘name<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> hname <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> mark <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> domain <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>’
<span class="token function">bash</span>
<span class="token comment">#命令行指定变量：</span>
ansible  websvrs  –e <span class="token assign-left variable">domain</span><span class="token operator">=</span>magedu.cn –m <span class="token function">hostname</span> –a    ‘name<span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> hname <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> mark <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> domain <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>’<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-9-template-模板"><a href="#3-9-template-模板" class="headerlink" title="3.9 template 模板"></a>3.9 template 模板</h4><p>模板是一个文本文件，可以做为生成文件的模版，并且模板文件中还可嵌套 jinja 语法</p>
<h5 id="3-9-1-jinja2-语言"><a href="#3-9-1-jinja2-语言" class="headerlink" title="3.9.1 jinja2 语言"></a>3.9.1 jinja2 语言</h5><p>网站：<code>https://jinja.palletsprojects.com/en/2.11.x/</code></p>
<p>jinja2 语言使用字面量，有下面形式：</p>
<p>字符串：使用单引号或双引号 </p>
<p>数字：整数，浮点数 </p>
<p>列表：[item1, item2, …] </p>
<p>元组：(item1, item2, …) </p>
<p>字典：{key1:value1, key2:value2, …} </p>
<p>布尔型：true&#x2F;false </p>
<p>算术运算：+, -, *, &#x2F;, &#x2F;&#x2F;, %, ** </p>
<p>比较操作：&#x3D;&#x3D;, !&#x3D;, &gt;, &gt;&#x3D;, &lt;, &lt;&#x3D; </p>
<p>逻辑运算：and，or，not </p>
<p>流表达式：For，If，When</p>
<p><strong>字面量</strong></p>
<p>表达式最简单的形式就是字面量。字面量表示诸如字符串和数值的 Python 对象。如 “Hello World” 双引号或单引号中间的一切都是字符串。无论何时你需要在模板中使用一个字符串（比如函数调用、过滤器或只是包含或继承一个模板的参数），如 42，42.23 </p>
<p>数值可以为整数和浮点数。如果有小数点，则为浮点数，否则为整数。在 Python 里， 42 和 42.0 是不一样的</p>
<p><strong>算术运算</strong></p>
<p><img src="https://gitee.com/miaohsukang/myblog/raw/master/img/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20230212191451.png"></p>
<p><strong>比较操作符</strong> </p>
<p>&#x3D;&#x3D; 比较两个对象是否相等 </p>
<p>!&#x3D; 比较两个对象是否不等</p>
<p>&gt; 如果左边大于右边，返回 true </p>
<p>&gt;&#x3D; 如果左边大于等于右边，返回 true </p>
<p>&lt; 如果左边小于右边，返回 true </p>
<p>&lt;&#x3D; 如果左边小于等于右边，返回 true</p>
<p><strong>逻辑运算符</strong> </p>
<p>对于 if 语句，在 for 过滤或 if 表达式中，它可以用于联合多个表达式 </p>
<p>and 如果左操作数和右操作数同为真，返回 true </p>
<p>or 如果左操作数和右操作数有一个为真，返回 true </p>
<p>not 对一个表达式取反 </p>
<p>(expr) 表达式组 </p>
<p>true &#x2F; false true 永远是 true ，而 false 始终是 false</p>
<h5 id="3-9-2-template"><a href="#3-9-2-template" class="headerlink" title="3.9.2 template"></a>3.9.2 template</h5><p>template 功能：可以根据和参考模块文件，动态生成相类似的配置文件 template 文件必须存放于 templates 目录下，且命名为 .j2 结尾 yaml&#x2F;yml 文件需和 templates 目录平级，目录结构如下示例：.&#x2F; ├── temnginx.yml └── templates └── nginx.conf.j2</p>
<p>范例：利用 template 同步 nginx 配置文件</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#准备templates/nginx.conf.j2文件</span>
<span class="token function">vim</span> temnginx.yml
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: template config to remote hosts
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf

 ansible-playbook temnginx.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>template 变更替换</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#修改文件nginx.conf.j2</span>
<span class="token function">mkdir</span> templates
<span class="token function">vim</span> templates/nginx.conf.j2
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> ansible_processor_vcpus <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

<span class="token function">vim</span> temnginx2.yml
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token function">install</span> nginx
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx
    - name: template config to remote hosts
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf
    - name: start <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enable</span><span class="token operator">=</span>yes

ansible-playbook temnginx2.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>template 算术运算</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> nginx.conf.j2
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> ansible_processor_vcpus**2 <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> ansible_processor_vcpus+2 <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ansible<span class="token punctuation">]</span><span class="token comment">#vim templates/nginx.conf.j2</span>
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> ansible_processor_vcpus**3 <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token punctuation">;</span>

<span class="token punctuation">[</span>root@ansible ansible<span class="token punctuation">]</span><span class="token comment">#cat templnginx.yml</span>
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token function">install</span> nginx
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx
    - name: template config to remote hosts
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf
      notify: restart nginx
    - name: start <span class="token function">service</span>
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes

  handlers:
    - name: restart nginx
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>restarted


ansible-playbook  templnginx.yml <span class="token parameter variable">--limit</span> <span class="token number">10.0</span>.0.8<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="3-9-3-template-中使用流程控制-for-和-if"><a href="#3-9-3-template-中使用流程控制-for-和-if" class="headerlink" title="3.9.3 template 中使用流程控制 for 和 if"></a>3.9.3 template 中使用流程控制 for 和 if</h5><p>template 中也可以使用流程控制 for 循环和 if 条件判断，实现动态生成文件功能</p>
<p>范例1：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#temlnginx2.yml</span>
---
- hosts: websrvs
  remote_user: root
  vars:
    nginx_vhosts:
      - <span class="token number">81</span>
      - <span class="token number">82</span>
      - <span class="token number">83</span>
  tasks:
    - name: template config
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/nginx.conf

<span class="token comment">#templates/nginx.conf2.j2</span>
<span class="token punctuation">&#123;</span>% <span class="token keyword">for</span> <span class="token for-or-select variable">vhost</span> <span class="token keyword">in</span>  nginx_vhosts %<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span>% endfor %<span class="token punctuation">&#125;</span>

ansible-playbook <span class="token parameter variable">-C</span>  templnginx2.yml  <span class="token parameter variable">--limit</span> <span class="token number">10.0</span>.0.8

<span class="token comment">#生成的结果：</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">81</span>
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">82</span>
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">83</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例2：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#temlnginx3.yml</span>
---
- hosts: websrvs
  remote_user: root
  vars:
    nginx_vhosts:
      - listen: <span class="token number">8080</span>
  tasks:
    - name: config <span class="token function">file</span>
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf3.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/nginx3.conf

<span class="token comment">#templates/nginx.conf3.j2</span>
<span class="token punctuation">&#123;</span>% <span class="token keyword">for</span> <span class="token for-or-select variable">vhost</span> <span class="token keyword">in</span> nginx_vhosts %<span class="token punctuation">&#125;</span>   
server <span class="token punctuation">&#123;</span>
  listen <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.listen <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span>% endfor %<span class="token punctuation">&#125;</span>


ansible-playbook   templnginx3.yml  <span class="token parameter variable">--limit</span> <span class="token number">10.0</span>.0.8

<span class="token comment">#生成的结果</span>
server <span class="token punctuation">&#123;</span>
  listen <span class="token number">8080</span>  
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范:3：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#templnginx4.yml</span>
- hosts: websrvs
  remote_user: root
  vars:
    nginx_vhosts:
      - listen: <span class="token number">8080</span>
        server_name: <span class="token string">"web1.magedu.com"</span>
        root: <span class="token string">"/var/www/nginx/web1/"</span>
      - listen: <span class="token number">8081</span>
        server_name: <span class="token string">"web2.magedu.com"</span>
        root: <span class="token string">"/var/www/nginx/web2/"</span>
      - <span class="token punctuation">&#123;</span>listen: <span class="token number">8082</span>, server_name: <span class="token string">"web3.magedu.com"</span>, root: <span class="token string">"/var/www/nginx/web3/"</span><span class="token punctuation">&#125;</span>
  tasks:
    - name: template config
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf4.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/nginx4.conf


<span class="token comment"># templates/nginx.conf4.j2</span>
<span class="token punctuation">&#123;</span>% <span class="token keyword">for</span> <span class="token for-or-select variable">vhost</span> <span class="token keyword">in</span> nginx_vhosts %<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.listen <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
   server_name <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.server_name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
   root <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.root <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>  
<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span>% endfor %<span class="token punctuation">&#125;</span>


ansible-playbook  templnginx4.yml <span class="token parameter variable">--limit</span> <span class="token number">10.0</span>.0.8

<span class="token comment">#生成结果：</span>
server <span class="token punctuation">&#123;</span>
    listen <span class="token number">8080</span>
    server_name web1.magedu.com
    root /var/www/nginx/web1/
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
    listen <span class="token number">8081</span>
    server_name web2.magedu.com
    root /var/www/nginx/web2/
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
    listen <span class="token number">8082</span>
    server_name web3.magedu.com
    root /var/www/nginx/web3/
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>在模版文件中还可以使用 if 条件判断，决定是否生成相关的配置信息</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#templnginx5.yml</span>
- hosts: websrvs
  remote_user: root
  vars:
    nginx_vhosts:
      - web1:
        listen: <span class="token number">8080</span>
        root: <span class="token string">"/var/www/nginx/web1/"</span>
      - web2:
        listen: <span class="token number">8080</span>
        server_name: <span class="token string">"web2.magedu.com"</span>
        root: <span class="token string">"/var/www/nginx/web2/"</span>
      - web3:
        listen: <span class="token number">8080</span>
        server_name: <span class="token string">"web3.magedu.com"</span>
        root: <span class="token string">"/var/www/nginx/web3/"</span>
  tasks:
    - name: template config to
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf5.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/data/nginx5.conf


<span class="token comment">#templates/nginx.conf5.j2</span>
<span class="token punctuation">&#123;</span>% <span class="token keyword">for</span> <span class="token for-or-select variable">vhost</span> <span class="token keyword">in</span>  nginx_vhosts %<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.listen <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#123;</span>% <span class="token keyword">if</span> vhost.server_name is defined %<span class="token punctuation">&#125;</span>
server_name <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.server_name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
   <span class="token punctuation">&#123;</span>% endif %<span class="token punctuation">&#125;</span>
root  <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> vhost.root <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#123;</span>% endfor %<span class="token punctuation">&#125;</span>

<span class="token comment">#生成的结果</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">8080</span>
   root  /var/www/nginx/web1/
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">8080</span>
   server_name web2.magedu.com
   root  /var/www/nginx/web2/
<span class="token punctuation">&#125;</span>
server <span class="token punctuation">&#123;</span>
   listen <span class="token number">8080</span>
   server_name web3.magedu.com
   root  /var/www/nginx/web3/
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-10-playbook-使用-when"><a href="#3-10-playbook-使用-when" class="headerlink" title="3.10 playbook 使用 when"></a>3.10 playbook 使用 when</h4><p>when 语句，可以实现条件测试。如果需要根据变量、facts 或此前任务的执行结果来做为某 task 执行与否的前提时要用到条件测试, 通过在 task 后添加 when 子句即可使用条件测试，jinja2 的语法格式</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: <span class="token string">"shutdown RedHat flavored systems"</span>
      command: /sbin/shutdown <span class="token parameter variable">-h</span> now
      when: ansible_os_family <span class="token operator">==</span> <span class="token string">"RedHat"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: <span class="token function">add</span> group nginx
      tags: user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: <span class="token function">add</span> user nginx
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">group</span><span class="token operator">=</span>nginx
    - name: Install Nginx
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>present
    - name: restart Nginx
      service: <span class="token assign-left variable">name</span><span class="token operator">=</span>nginx <span class="token assign-left variable">state</span><span class="token operator">=</span>restarted
      when: ansible_distribution_major_version <span class="token operator">==</span> “6”<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  tasks: 
    - name: <span class="token function">install</span> conf <span class="token function">file</span> to centos7
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.c7.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf
      when: ansible_distribution_major_version <span class="token operator">==</span> <span class="token string">"7"</span>
    - name: <span class="token function">install</span> conf <span class="token function">file</span> to centos6
      template: <span class="token assign-left variable">src</span><span class="token operator">=</span>nginx.conf.c6.j2 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/nginx/nginx.conf
      when: ansible_distribution_major_version <span class="token operator">==</span> <span class="token string">"6"</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-11-playbook-使用迭代-with-items"><a href="#3-11-playbook-使用迭代-with-items" class="headerlink" title="3.11 playbook 使用迭代 with_items"></a>3.11 playbook 使用迭代 with_items</h4><p>迭代：当有需要重复性执行的任务时，可以使用迭代机制 对迭代项的引用，固定变量名为”item“ 要在 task 中使用 with_items 给定要迭代的元素列表</p>
<p>列表元素格式：</p>
<ul>
<li>字符串</li>
<li>字典</li>
</ul>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token function">add</span> several <span class="token function">users</span>
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">groups</span><span class="token operator">=</span>wheel
      with_items:
        - testuser1
        - testuser2
<span class="token comment">#上面语句的功能等同于下面的语句</span>
    - name: <span class="token function">add</span> user testuser1
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>testuser1 <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">groups</span><span class="token operator">=</span>wheel
    - name: <span class="token function">add</span> user testuser2
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>testuser2 <span class="token assign-left variable">state</span><span class="token operator">=</span>present <span class="token assign-left variable">groups</span><span class="token operator">=</span>wheel<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
<span class="token comment">#remove mariadb server</span>
- hosts: appsrvs:<span class="token operator">!</span><span class="token number">192.168</span>.38.8
  remote_user: root

  tasks:
    - name: stop <span class="token function">service</span>
      shell: /etc/init.d/mysqld stop
    - name:  delete files and <span class="token function">dir</span>
      file: <span class="token assign-left variable">path</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>item<span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>absent
      with_items:
        - /usr/local/mysql
        - /usr/local/mariadb-10.2.27-linux-x86_64
        - /etc/init.d/mysqld
        - /etc/profile.d/mysql.sh
        - /etc/my.cnf
        - /data/mysql
    - name: delete user
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>absent <span class="token assign-left variable">remove</span><span class="token operator">=</span>yes<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts：websrvs
  remote_user: root

  tasks
    - name: <span class="token function">install</span> some packages
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - nginx
        - memcached
        - php-fpm<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  tasks:
    - name: copy <span class="token function">file</span>
      copy: <span class="token assign-left variable">src</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">dest</span><span class="token operator">=</span>/tmp/<span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>
      with_items:
        - file1
        - file2
        - file3
    - name: yum <span class="token function">install</span> httpd
      yum: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>  <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - apr
        - apr-util
        - httpd<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>迭代嵌套子变量：</strong>在迭代中，还可以嵌套子变量，关联多个变量在一起使用</p>
<p>示例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token function">add</span> some <span class="token function">groups</span>
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - nginx
        - mysql
        - apache
    - name: <span class="token function">add</span> some <span class="token function">users</span>
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item.name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">group</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item.group <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'nginx'</span>, group: <span class="token string">'nginx'</span> <span class="token punctuation">&#125;</span>
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'mysql'</span>, group: <span class="token string">'mysql'</span> <span class="token punctuation">&#125;</span>
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'apache'</span>, group: <span class="token string">'apache'</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">cat</span> with_item2.yml
---
- hosts: websrvs
  remote_user: root

  tasks:
    - name: <span class="token function">add</span> some <span class="token function">groups</span>
      group: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - g1
        - g2
        - g3
    - name: <span class="token function">add</span> some <span class="token function">users</span>
      user: <span class="token assign-left variable">name</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item.name <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">group</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item.group <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">home</span><span class="token operator">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> item.home <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span> <span class="token assign-left variable">create_home</span><span class="token operator">=</span>yes <span class="token assign-left variable">state</span><span class="token operator">=</span>present
      with_items:
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'user1'</span>, group: <span class="token string">'g1'</span>, home: <span class="token string">'/data/user1'</span> <span class="token punctuation">&#125;</span>
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'user2'</span>, group: <span class="token string">'g2'</span>, home: <span class="token string">'/data/user2'</span> <span class="token punctuation">&#125;</span>
        - <span class="token punctuation">&#123;</span> name: <span class="token string">'user3'</span>, group: <span class="token string">'g3'</span>, home: <span class="token string">'/data/user3'</span> <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="3-12-管理节点过多导致的超时问题解决方法"><a href="#3-12-管理节点过多导致的超时问题解决方法" class="headerlink" title="3.12 管理节点过多导致的超时问题解决方法"></a>3.12 管理节点过多导致的超时问题解决方法</h4><p>默认情况下，Ansible 将尝试并行管理 playbook 中所有的机器。对于滚动更新用例，可以使用 serial 关键字定义 Ansible 一次应管理多少主机，还可以将 serial 关键字指定为百分比，表示每次并行执行的主机数占总数的比例</p>
<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token comment">#vim test_serial.yml</span>
---
- hosts: all
  serial: <span class="token number">2</span>  <span class="token comment">#每次只同时处理2个主机</span>
  gather_facts: False

  tasks:
    - name: task one
      comand: <span class="token function">hostname</span>
    - name: task two
      command: <span class="token function">hostname</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>范例：</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">- name: <span class="token builtin class-name">test</span> serail
  hosts: all
  serial: <span class="token string">"20%"</span>   <span class="token comment">#每次只同时处理20%的主机</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<h3 id="四-、Roles-角色"><a href="#四-、Roles-角色" class="headerlink" title="四 、Roles 角色"></a>四 、Roles 角色</h3><p><img src="https://gitee.com/miaohsukang/myblog/raw/master/img/20201027202522657.PNG"></p>
<p>角色是 ansible 自 1.2 版本引入的新特性，用于层次性、结构化地组织 playbook。roles 能够根据层次型结构自动装载变量文件、tasks 以及 handlers 等。要使用 roles 只需要在 playbook 中使用 include 指令即可。简单来讲，roles 就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中，并可以便捷地 include 它们的一种机制。角色一般用于基于主机构建服务的场景中，但也可以是用于构建守护进程等场景中</p>
<p>运维复杂的场景：建议使用 roles，代码复用度高</p>
<p>roles：多个角色的集合， 可以将多个的 role，分别放至 roles 目录下的独立子目录中 </p>
<p>roles&#x2F; </p>
<p>​		mysql&#x2F; </p>
<p>​		httpd&#x2F; </p>
<p>​		nginx&#x2F; </p>
<p>​		redis&#x2F;</p>
<h4 id="4-1-Ansible-Roles-目录编排"><a href="#4-1-Ansible-Roles-目录编排" class="headerlink" title="4.1 Ansible Roles 目录编排"></a>4.1 Ansible Roles 目录编排</h4><p>roles 目录结构如下所示</p>
<p><img src="https://gitee.com/miaohsukang/myblog/raw/master/img/OIP-C.gazp9scc1C7r_HBIbM92ZgHaGT"></p>
<p>每个角色，以特定的层级目录结构进行组织</p>
<p><strong>roles 目录结构：</strong> </p>
<p>playbook.yml </p>
<p>roles&#x2F; </p>
<p>​	project&#x2F; </p>
<p>​		tasks&#x2F; </p>
<p>​		files&#x2F; </p>
<p>​		vars&#x2F;<br>templates&#x2F; </p>
<p>handlers&#x2F; </p>
<p>default&#x2F;<br>meta&#x2F;</p>
<p><strong>Roles 各目录作用</strong> </p>
<p>roles&#x2F;project&#x2F; : 项目名称, 有以下子目录</p>
<ul>
<li>files&#x2F; ：存放由 copy 或 script 模块等调用的文件</li>
<li>templates&#x2F;：template 模块查找所需要模板文件的目录</li>
<li>tasks&#x2F;：定义 task,role 的基本元素，至少应该包含一个名为 main.yml 的文件；其它的文件需要在此文件中通过 include 进行包含</li>
<li>handlers&#x2F;：至少应该包含一个名为 main.yml 的文件；其它的文件需要在此文件中通过 include 进行包含</li>
<li>vars&#x2F;：定义变量，至少应该包含一个名为 main.yml 的文件；其它的文件需要在此文件中通过 include 进行包含</li>
<li>meta&#x2F;：定义当前角色的特殊设定及其依赖关系, 至少应该包含一个名为 main.yml 的文件，其它文件需在此文件中通过 include 进行包含</li>
<li>default&#x2F;：设定默认变量时使用此目录中的 main.yml 文件，比 vars 的优先级低</li>
</ul>
<h4 id="4-2-创建-role"><a href="#4-2-创建-role" class="headerlink" title="4.2 创建 role"></a>4.2 创建 role</h4><p>创建 role 的步骤 (1) 创建以 roles 命名的目录 (2) 在 roles 目录中分别创建以各角色名称命名的目录，如 webservers 等 (3) 在每个角色命名的目录中分别创建 files、handlers、meta、tasks、templates 和 vars 目录；用不到的目录可以创建为空目录，也可以不创建 (4) 在 playbook 文件中，调用各角色</p>
<p>针对大型项目使用 Roles 进行编排 范例：roles 的目录结构</p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">nginx-role.yml
roles/
└── nginx
     ├── files
     │    └── main.yml
     ├── tasks
     │    ├── groupadd.yml
     │    ├── install.yml
     │    ├── main.yml
     │    ├── restart.yml
     │    └── useradd.yml
     └── vars
          └── main.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="4-3-playbook-调用角色"><a href="#4-3-playbook-调用角色" class="headerlink" title="4.3 playbook 调用角色"></a>4.3 playbook 调用角色</h4><p><strong>调用角色方法 1：</strong></p>
<pre class="line-numbers language-bash" data-language="bash"><code class="language-bash">---
- hosts: websrvs
  remote_user: root
  roles:
    - mysql
    - memcached
    - nginx<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>调用角色方法 2：</strong></p>
<p>键 role 用于指定角色名称，后续的 k&#x2F;v 用于传递变量给角色</p>
<pre class="line-numbers language-none"><code class="language-none">---
- hosts: all
  remote_user: root
  roles:
    - mysql
    - &#123; role: nginx, username: nginx &#125;<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p><strong>调用角色方法 3：</strong></p>
<p>还可基于条件测试实现角色调用</p>
<pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml"><span class="token punctuation">---</span>
<span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span> all
  <span class="token key atrule">remote_user</span><span class="token punctuation">:</span> root
  <span class="token key atrule">roles</span><span class="token punctuation">:</span>
    <span class="token punctuation">-</span> <span class="token punctuation">&#123;</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> nginx<span class="token punctuation">,</span> <span class="token key atrule">username</span><span class="token punctuation">:</span> nginx<span class="token punctuation">,</span> <span class="token key atrule">when</span><span class="token punctuation">:</span> ansible_distribution_major_version == ‘7’  <span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="4-4-roles-中-tags-使用"><a href="#4-4-roles-中-tags-使用" class="headerlink" title="4.4 roles 中 tags 使用"></a>4.4 roles 中 tags 使用</h4><pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml"><span class="token comment">#nginx-role.yml</span>
<span class="token punctuation">---</span>
<span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span> websrvs
  <span class="token key atrule">remote_user</span><span class="token punctuation">:</span> root
  <span class="token key atrule">roles</span><span class="token punctuation">:</span>
    <span class="token punctuation">-</span> <span class="token punctuation">&#123;</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> nginx <span class="token punctuation">,</span><span class="token key atrule">tags</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token string">'nginx'</span><span class="token punctuation">,</span> <span class="token string">'web'</span> <span class="token punctuation">]</span> <span class="token punctuation">,</span><span class="token key atrule">when</span><span class="token punctuation">:</span> ansible_distribution_major_version == "6“ <span class="token punctuation">&#125;</span>
    <span class="token punctuation">-</span> <span class="token punctuation">&#123;</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> httpd <span class="token punctuation">,</span><span class="token key atrule">tags</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token string">'httpd'</span><span class="token punctuation">,</span> <span class="token string">'web'</span> <span class="token punctuation">]</span>  <span class="token punctuation">&#125;</span>
    <span class="token punctuation">-</span> <span class="token punctuation">&#123;</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> mysql <span class="token punctuation">,</span><span class="token key atrule">tags</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token string">'mysql'</span><span class="token punctuation">,</span> <span class="token string">'db'</span> <span class="token punctuation">]</span> <span class="token punctuation">&#125;</span>
    <span class="token punctuation">-</span> <span class="token punctuation">&#123;</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> mariadb <span class="token punctuation">,</span><span class="token key atrule">tags</span><span class="token punctuation">:</span> <span class="token punctuation">[</span> <span class="token string">'mariadb'</span><span class="token punctuation">,</span> <span class="token string">'db'</span> <span class="token punctuation">]</span> <span class="token punctuation">&#125;</span>

ansible<span class="token punctuation">-</span>playbook <span class="token punctuation">-</span><span class="token punctuation">-</span>tags="nginx<span class="token punctuation">,</span>httpd<span class="token punctuation">,</span>mysql" nginx<span class="token punctuation">-</span>role.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h4 id="4-5-实战案例"><a href="#4-5-实战案例" class="headerlink" title="4.5 实战案例"></a>4.5 实战案例</h4><h5 id="4-5-1-案例-1：实现-httpd-角色"><a href="#4-5-1-案例-1：实现-httpd-角色" class="headerlink" title="4.5.1 案例 1：实现 httpd 角色"></a>4.5.1 案例 1：实现 httpd 角色</h5><pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml"><span class="token comment">#创建角色相关的目录</span>
mkdir <span class="token punctuation">-</span>pv /data/ansible/roles/httpd/<span class="token punctuation">&#123;</span>tasks<span class="token punctuation">,</span>handlers<span class="token punctuation">,</span>files<span class="token punctuation">&#125;</span>

<span class="token comment">#创建角色相关的文件</span>
cd /data/ansible/roles/httpd/

vim tasks/main.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> group.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> user.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> install.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> config.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> index.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> service.yml

vim  tasks/user.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> create apache user
  <span class="token key atrule">user</span><span class="token punctuation">:</span> name=apache system=yes shell=/sbin/nologin home=/var/www/ uid=80 group=apache

vim  tasks/group.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> create apache group
  <span class="token key atrule">group</span><span class="token punctuation">:</span> name=apache system=yes gid=80


vim tasks/install.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> install httpd package
  <span class="token key atrule">yum</span><span class="token punctuation">:</span> name=httpd

vim tasks/config.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> config file
  <span class="token key atrule">copy</span><span class="token punctuation">:</span> src=httpd.conf dest=/etc/httpd/conf/ backup=yes
  <span class="token key atrule">notify</span><span class="token punctuation">:</span> restart

vim tasks/index.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> index.html
  <span class="token key atrule">copy</span><span class="token punctuation">:</span> src=index.html dest=/var/www/html/

vim tasks/service.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> start service
  <span class="token key atrule">service</span><span class="token punctuation">:</span> name=httpd state=started enabled=yes

vim handlers/main.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> restart
  <span class="token key atrule">service</span><span class="token punctuation">:</span> name=httpd state=restarted

<span class="token comment">#在files目录下准备两个文件</span>
ls files/
httpd.conf index.html

tree /data/ansible/roles/httpd/
/data/ansible/roles/httpd/
├── files
│   ├── httpd.conf
│   └── index.html
├── handlers
│   └── main.yml
└── tasks
    ├── config.yml
    ├── group.yml
    ├── index.yml
    ├── install.yml
    ├── main.yml
    ├── service.yml
    └── user.yml

3 directories<span class="token punctuation">,</span> 10 files


<span class="token comment">#在playbook中调用角色，与role平级</span>
vim  /data/ansible/role_httpd.yml
<span class="token punctuation">---</span>
<span class="token comment"># httpd role</span>
<span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span> websrvs
  <span class="token key atrule">remote_user</span><span class="token punctuation">:</span> root

  <span class="token key atrule">roles</span><span class="token punctuation">:</span>
    <span class="token punctuation">-</span> httpd

<span class="token comment">#运行playbook</span>
ansible<span class="token punctuation">-</span>playbook  /data/ansible/role_httpd.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="4-5-2-案例-2：实现-nginx-角色"><a href="#4-5-2-案例-2：实现-nginx-角色" class="headerlink" title="4.5.2 案例 2：实现 nginx 角色"></a>4.5.2 案例 2：实现 nginx 角色</h5><pre class="line-numbers language-yaml" data-language="yaml"><code class="language-yaml">mkdir <span class="token punctuation">-</span>pv  /data/ansible/roles/nginx/<span class="token punctuation">&#123;</span>tasks<span class="token punctuation">,</span>handlers<span class="token punctuation">,</span>templates<span class="token punctuation">,</span>vars<span class="token punctuation">&#125;</span>

<span class="token comment">#创建task文件</span>
cd /data/ansible/roles/nginx/

vim tasks/main.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> install.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> config.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> index.yml
<span class="token punctuation">-</span> <span class="token key atrule">include</span><span class="token punctuation">:</span> service.yml

vim  tasks/install.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> install
  <span class="token key atrule">yum</span><span class="token punctuation">:</span> name=nginx

vim tasks/config.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> config file for centos7
  <span class="token key atrule">template</span><span class="token punctuation">:</span> src=nginx7.conf.j2 dest=/etc/nginx/nginx.conf
  <span class="token key atrule">when</span><span class="token punctuation">:</span> ansible_distribution_major_version=="7"
  <span class="token key atrule">notify</span><span class="token punctuation">:</span> restart
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> config file for centos8
  <span class="token key atrule">template</span><span class="token punctuation">:</span> src=nginx8.conf.j2 dest=/etc/nginx/nginx.conf
  <span class="token key atrule">when</span><span class="token punctuation">:</span> ansible_distribution_major_version=="8"
  <span class="token key atrule">notify</span><span class="token punctuation">:</span> restart

vim  tasks/index.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> index.html
  <span class="token key atrule">copy</span><span class="token punctuation">:</span> src=roles/httpd/files/index.html dest=/usr/share/nginx/html/

vim tasks/service.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> start service
  <span class="token key atrule">service</span><span class="token punctuation">:</span> name=nginx state=started enabled=yes

<span class="token comment">#创建handler文件</span>
cat handlers/main.yml
<span class="token punctuation">-</span> <span class="token key atrule">name</span><span class="token punctuation">:</span> restart
  <span class="token key atrule">service</span><span class="token punctuation">:</span> name=nginx state=restarted

<span class="token comment">#创建两个template文件</span>
cat templates/nginx7.conf.j2
<span class="token punctuation">...</span>省略<span class="token punctuation">...</span>
user <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>user<span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>;
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>ansible_processor_vcpus+3<span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>;   <span class="token comment">#修改此行</span>
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
<span class="token punctuation">...</span>省略<span class="token punctuation">...</span>


cat templates/nginx8.conf.j2
<span class="token punctuation">...</span>省略<span class="token punctuation">...</span>
user nginx;
worker_processes <span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>ansible_processor_vcpus<span class="token important">**3</span><span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span>;  <span class="token comment">#修改此行</span>
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
<span class="token punctuation">...</span>省略<span class="token punctuation">...</span>

<span class="token comment">#创建变量文件</span>
vim vars/main.yml
<span class="token key atrule">user</span><span class="token punctuation">:</span> daemon


<span class="token comment">#目录结构如下</span>

tree /data/ansible/roles/nginx/
/data/ansible/roles/nginx/
├── handlers
│   └── main.yml
├── tasks
│   ├── config.yml
│   ├── file.yml
│   ├── install.yml
│   ├── main.yml
│   └── service.yml
├── templates
│   ├── nginx7.conf.j2
│   └── nginx8.conf.j2
└── vars
    └── main.yml

4 directories<span class="token punctuation">,</span> 9 files


<span class="token comment">#在playbook中调用角色</span>
vim /data/ansible/role_nginx.yml
<span class="token punctuation">---</span>
<span class="token comment">#nginx role</span>
<span class="token punctuation">-</span> <span class="token key atrule">hosts</span><span class="token punctuation">:</span> websrvs

  <span class="token key atrule">roles</span><span class="token punctuation">:</span>
    <span class="token punctuation">-</span> <span class="token key atrule">role</span><span class="token punctuation">:</span> nginx

<span class="token comment">#运行playbook</span>
ansible<span class="token punctuation">-</span>playbook  /data/ansible/role_nginx.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="4-5-3-案例-3：实现-memcached-角色"><a href="#4-5-3-案例-3：实现-memcached-角色" class="headerlink" title="4.5.3 案例 3：实现 memcached 角色"></a>4.5.3 案例 3：实现 memcached 角色</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">mkdir</span> <span class="token parameter variable">-pv</span>  /data/ansible/roles/memcached/<span class="token punctuation">&#123;</span>tasks,templates<span class="token punctuation">&#125;</span>

<span class="token builtin class-name">cd</span> /data/ansible/roles/memcached
<span class="token function">vim</span> tasks/main.yml
- include: install.yml
- include: config.yml
- include: service.yml

<span class="token function">vim</span> tasks/install.yml
- name: <span class="token function">install</span>
  yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>memcached

<span class="token function">vim</span> tasks/config.yml
- name: config <span class="token function">file</span>
  template: <span class="token assign-left variable">src</span><span class="token operator">=</span>memcached.j2  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/sysconfig/memcached

<span class="token function">vim</span> tasks/service.yml
- name: <span class="token function">service</span>
  service: <span class="token assign-left variable">name</span><span class="token operator">=</span>memcached <span class="token assign-left variable">state</span><span class="token operator">=</span>started <span class="token assign-left variable">enabled</span><span class="token operator">=</span>yes

<span class="token function">vim</span> templates/memcached.j2
<span class="token assign-left variable">PORT</span><span class="token operator">=</span><span class="token string">"11211"</span>
<span class="token assign-left variable"><span class="token environment constant">USER</span></span><span class="token operator">=</span><span class="token string">"memcached"</span>
<span class="token assign-left variable">MAXCONN</span><span class="token operator">=</span><span class="token string">"1024"</span>
<span class="token assign-left variable">CACHESIZE</span><span class="token operator">=</span><span class="token string">"&#123;&#123;ansible_memtotal_mb//4&#125;&#125;"</span>
<span class="token assign-left variable">OPTIONS</span><span class="token operator">=</span><span class="token string">""</span>

tree /data/ansible/roles/memcached/
/data/ansible/roles/memcached/
├── tasks
│   ├── config.yml
│   ├── install.yml
│   ├── main.yml
│   └── service.yml
└── templates
    └── memcached.j2

<span class="token number">2</span> directories, <span class="token number">5</span> files

<span class="token function">vim</span> /data/ansible/role_memcached.yml
---
- hosts: appsrvs

  roles:
    - role: memcached


ansible-play /data/ansible/role_memcached.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="4-5-4-案例-4：实现-mysql-5-6-的角色"><a href="#4-5-4-案例-4：实现-mysql-5-6-的角色" class="headerlink" title="4.5.4 案例 4：实现 mysql 5.6 的角色"></a>4.5.4 案例 4：实现 mysql 5.6 的角色</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/files/my.cnf</span>
<span class="token punctuation">[</span>mysqld<span class="token punctuation">]</span>
<span class="token assign-left variable">socket</span><span class="token operator">=</span>/tmp/mysql.sock
<span class="token assign-left variable">user</span><span class="token operator">=</span>mysql
symbolic-links<span class="token operator">=</span><span class="token number">0</span>
<span class="token assign-left variable">datadir</span><span class="token operator">=</span>/data/mysql
<span class="token assign-left variable">innodb_file_per_table</span><span class="token operator">=</span><span class="token number">1</span>
log-bin
pid-file<span class="token operator">=</span>/data/mysql/mysqld.pid

<span class="token punctuation">[</span>client<span class="token punctuation">]</span>
<span class="token assign-left variable">port</span><span class="token operator">=</span><span class="token number">3306</span>
<span class="token assign-left variable">socket</span><span class="token operator">=</span>/tmp/mysql.sock

<span class="token punctuation">[</span>mysqld_safe<span class="token punctuation">]</span>
log-error<span class="token operator">=</span>/var/log/mysqld.log

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/files/secure_mysql.sh</span>
<span class="token comment">#!/bin/bash</span>
/usr/local/mysql/bin/mysql_secure_installation <span class="token operator">&lt;&lt;</span><span class="token string">EOF

y
magedu
magedu
y
y
y
y
EOF</span>

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#chmod +x  /data/ansible/roles/mysql/files/secure_mysql.sh</span>

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ls /data/ansible/roles/mysql/files/</span>
my.cnf  mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz  secure_mysql.sh

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/main.yml</span>
- include: install.yml
- include: group.yml
- include: user.yml
- include: unarchive.yml
- include: link.yml
- include: data.yml
- include: config.yml
- include: service.yml
- include: path.yml
- include: secure.yml

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/install.yml</span>
- name: <span class="token function">install</span> packages
  yum: <span class="token assign-left variable">name</span><span class="token operator">=</span>libaio,perl-Data-Dumper,perl-Getopt-Long
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/group.yml</span>
- name: create mysql group
  group: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">gid</span><span class="token operator">=</span><span class="token number">306</span>
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/user.yml</span>
- name: create mysql user
  user: <span class="token assign-left variable">name</span><span class="token operator">=</span>mysql <span class="token assign-left variable">uid</span><span class="token operator">=</span><span class="token number">306</span> <span class="token assign-left variable">group</span><span class="token operator">=</span>mysql <span class="token assign-left variable">shell</span><span class="token operator">=</span>/sbin/nologin <span class="token assign-left variable">system</span><span class="token operator">=</span>yes <span class="token assign-left variable">create_home</span><span class="token operator">=</span>no <span class="token assign-left variable">home</span><span class="token operator">=</span>/data/mysql
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/unarchive.yml</span>
- name: copy <span class="token function">tar</span> to remote <span class="token function">host</span> and <span class="token function">file</span> mode
  unarchive: <span class="token assign-left variable">src</span><span class="token operator">=</span>mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/local/ <span class="token assign-left variable">owner</span><span class="token operator">=</span>root <span class="token assign-left variable">group</span><span class="token operator">=</span>root
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/link.yml</span>
- name: <span class="token function">mkdir</span> /usr/local/mysql
  file: <span class="token assign-left variable">src</span><span class="token operator">=</span>/usr/local/mysql-5.6.46-linux-glibc2.12-x86_64 <span class="token assign-left variable">dest</span><span class="token operator">=</span>/usr/local/mysql <span class="token assign-left variable">state</span><span class="token operator">=</span>link
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/data.yml</span>
- name: data <span class="token function">dir</span>
  shell: <span class="token assign-left variable">chdir</span><span class="token operator">=</span>/usr/local/mysql/  ./scripts/mysql_install_db <span class="token parameter variable">--datadir</span><span class="token operator">=</span>/data/mysql <span class="token parameter variable">--user</span><span class="token operator">=</span>mysql
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/config.yml</span>
- name: config my.cnf
  copy: <span class="token assign-left variable">src</span><span class="token operator">=</span>my.cnf  <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/my.cnf
<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/service.yml</span>
- name: <span class="token function">service</span> script
  shell: /bin/cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld<span class="token punctuation">;</span><span class="token function">chkconfig</span> <span class="token parameter variable">--add</span> mysqld<span class="token punctuation">;</span><span class="token function">chkconfig</span> mysqld on<span class="token punctuation">;</span>/etc/init.d/mysqld start

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/path.yml</span>
- name: <span class="token environment constant">PATH</span> variable
  copy: <span class="token assign-left variable">content</span><span class="token operator">=</span><span class="token string">'PATH=/usr/local/mysql/bin:$PATH'</span> <span class="token assign-left variable">dest</span><span class="token operator">=</span>/etc/profile.d/mysql.sh

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/roles/mysql/tasks/secure.yml</span>
- name: secure script
  script: secure_mysql.sh

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#tree /data/ansible/roles/mysql/</span>
/data/ansible/roles/mysql/
├── files
│   ├── my.cnf
│   ├── mysql-5.6.46-linux-glibc2.12-x86_64.tar.gz
│   └── secure_mysql.sh
└── tasks
    ├── config.yml
    ├── data.yml
    ├── group.yml
    ├── install.yml
    ├── link.yml
    ├── main.yml
    ├── path.yml
    ├── secure.yml
    ├── service.yml
    ├── unarchive.yml
    └── user.yml

<span class="token number">2</span> directories, <span class="token number">14</span> files

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#cat /data/ansible/mysql_roles.yml</span>
- hosts: dbsrvs
  remote_user: root

  roles:
    - <span class="token punctuation">&#123;</span>role: mysql,tags: <span class="token punctuation">[</span><span class="token string">"mysql"</span>,<span class="token string">"db"</span><span class="token punctuation">]</span><span class="token punctuation">&#125;</span>
    - <span class="token punctuation">&#123;</span>role: nginx,tage: <span class="token punctuation">[</span><span class="token string">"nginx"</span>,<span class="token string">"web"</span><span class="token punctuation">]</span><span class="token punctuation">&#125;</span>

<span class="token punctuation">[</span>root@ansible ~<span class="token punctuation">]</span><span class="token comment">#ansible-playbook -t mysql /data/ansible/mysql_roles.yml</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<h5 id="4-5-5-案例-5-：实现多角色的选择"><a href="#4-5-5-案例-5-：实现多角色的选择" class="headerlink" title="4.5.5 案例 5 ：实现多角色的选择"></a>4.5.5 案例 5 ：实现多角色的选择</h5><pre class="line-numbers language-bash" data-language="bash"><code class="language-bash"><span class="token function">vim</span> /data/ansible/role_httpd_nginx.yml
---
- hosts: websrvs

  roles:
    - <span class="token punctuation">&#123;</span>role: httpd,tags: <span class="token punctuation">[</span>httpd,web<span class="token punctuation">]</span>, when: <span class="token assign-left variable">ansible_distribution_major_version</span><span class="token operator">==</span><span class="token string">"7"</span> <span class="token punctuation">&#125;</span>
    - <span class="token punctuation">&#123;</span>role: nginx,tags: <span class="token punctuation">[</span>nginx,web<span class="token punctuation">]</span>, when: <span class="token assign-left variable">ansible_distribution_major_version</span><span class="token operator">==</span><span class="token string">"8"</span> <span class="token punctuation">&#125;</span>

ansible-playbook <span class="token parameter variable">-t</span> nginx /data/ansible/role_httpd_nginx.yml<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

                
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Miaohsukang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://miaohsukang.gitee.io/2023/02/12/ansible/ansible-ru-men/">https://miaohsukang.gitee.io/2023/02/12/ansible/ansible-ru-men/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Miaohsukang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/ansible/">
                                    <span class="chip bg-color">ansible</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2023/02/12/docker/an-zhuang-docker/">
                    <div class="card-image">
                        
                        <img src="https://www.lixuan222.com/wp-content/uploads/2020/07/docker.png" class="responsive-img" alt="安装docker">
                        
                        <span class="card-title">安装docker</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2023-02-12
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Docker/" class="post-category">
                                    Docker
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/docker/">
                        <span class="chip bg-color">docker</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2023/02/12/linux/linux-xiang-guan-scsi-ming-ling/">
                    <div class="card-image">
                        
                        <img src="https://img.javatt.com/c2/c2d1366f6c38d9e329f0a0cad7612480.png" class="responsive-img" alt="Linux相关scsi命令">
                        
                        <span class="card-title">Linux相关scsi命令</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2023-02-12
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Linux/" class="post-category">
                                    Linux
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/linux-scsi/">
                        <span class="chip bg-color">linux-scsi</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>


  <!-- 是否加载使用自带的 prismjs. -->
  <script type="text/javascript" src="/libs/prism/prism.min.js"></script>


<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>



    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\\(', '\\)']]}
    });
</script>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="/libs/aplayer/Meting.min.js"></script>

    

    <div class="container row center-align"
         style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2023</span>
            
            <a href="/about" target="_blank">Miaohsukang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://miaohsukang.gitee.io" target="_blank">Matery</a>
            
            <br>
            
            
            
                
            
            
                <span id="busuanzi_container_site_pv">
                &nbsp;|&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;
                    <span id="busuanzi_value_site_pv" class="white-color"></span>
            </span>
            
            
                <span id="busuanzi_container_site_uv">
                &nbsp;|&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;
                    <span id="busuanzi_value_site_uv" class="white-color"></span>
            </span>
            
            <br>

            <!-- 运行天数提醒. -->
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://miaohsukang.gitee.io" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:12419315+miaohsukang@user.noreply.gitee.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>



    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=258603904" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 258603904" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script type="text/javascript">
$(function () {
    var searchFunc = function (path, search_id, content_id) {
        'use strict';
        $.ajax({
            url: path,
            dataType: "xml",
            success: function (xmlResponse) {
                // get the contents from search data
                var datas = $("entry", xmlResponse).map(function () {
                    return {
                        title: $("title", this).text(),
                        content: $("content", this).text(),
                        url: $("url", this).text()
                    };
                }).get();
                var $input = document.getElementById(search_id);
                var $resultContent = document.getElementById(content_id);
                $input.addEventListener('input', function () {
                    var str = '<ul class=\"search-result-list\">';
                    var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                    $resultContent.innerHTML = "";
                    if (this.value.trim().length <= 0) {
                        return;
                    }
                    // perform local searching
                    datas.forEach(function (data) {
                        var isMatch = true;
                        var data_title = data.title.trim().toLowerCase();
                        var data_content = data.content.trim().replace(/<[^>]+>/g, "").toLowerCase();
                        var data_url = data.url;
                        data_url = data_url.indexOf('/') === 0 ? data.url : '/' + data_url;
                        var index_title = -1;
                        var index_content = -1;
                        var first_occur = -1;
                        // only match artiles with not empty titles and contents
                        if (data_title !== '' && data_content !== '') {
                            keywords.forEach(function (keyword, i) {
                                index_title = data_title.indexOf(keyword);
                                index_content = data_content.indexOf(keyword);
                                if (index_title < 0 && index_content < 0) {
                                    isMatch = false;
                                } else {
                                    if (index_content < 0) {
                                        index_content = 0;
                                    }
                                    if (i === 0) {
                                        first_occur = index_content;
                                    }
                                }
                            });
                        }
                        // show search results
                        if (isMatch) {
                            str += "<li><a href='" + data_url + "' class='search-result-title'>" + data_title + "</a>";
                            var content = data.content.trim().replace(/<[^>]+>/g, "");
                            if (first_occur >= 0) {
                                // cut out 100 characters
                                var start = first_occur - 20;
                                var end = first_occur + 80;
                                if (start < 0) {
                                    start = 0;
                                }
                                if (start === 0) {
                                    end = 100;
                                }
                                if (end > content.length) {
                                    end = content.length;
                                }
                                var match_content = content.substr(start, end);
                                // highlight all keywords
                                keywords.forEach(function (keyword) {
                                    var regS = new RegExp(keyword, "gi");
                                    match_content = match_content.replace(regS, "<em class=\"search-keyword\">" + keyword + "</em>");
                                });

                                str += "<p class=\"search-result\">" + match_content + "...</p>"
                            }
                            str += "</li>";
                        }
                    });
                    str += "</ul>";
                    $resultContent.innerHTML = str;
                });
            }
        });
    };

    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 白天和黑夜主题 -->
<div class="stars-con">
    <div id="stars"></div>
    <div id="stars2"></div>
    <div id="stars3"></div>  
</div>

<script>
    function switchNightMode() {
        $('<div class="Cuteen_DarkSky"><div class="Cuteen_DarkPlanet"></div></div>').appendTo($('body')),
        setTimeout(function () {
            $('body').hasClass('DarkMode') 
            ? ($('body').removeClass('DarkMode'), localStorage.setItem('isDark', '0'), $('#sum-moon-icon').removeClass("fa-sun").addClass('fa-moon')) 
            : ($('body').addClass('DarkMode'), localStorage.setItem('isDark', '1'), $('#sum-moon-icon').addClass("fa-sun").removeClass('fa-moon')),
            
            setTimeout(function () {
            $('.Cuteen_DarkSky').fadeOut(1e3, function () {
                $(this).remove()
            })
            }, 2e3)
        })
    }
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    

    
    
    

    <!-- 雪花特效 -->
    

    <!-- 鼠标星星特效 -->
    

     
        <script src="https://ssl.captcha.qq.com/TCaptcha.js"></script>
        <script src="/libs/others/TencentCaptcha.js"></script>
        <button id="TencentCaptcha" data-appid="xxxxxxxxxx" data-cbfn="callback" type="button" hidden></button>
    

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    <!--腾讯兔小巢-->
    
    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
